Simple Basics and Tips
Simple Basics and Tips
PROGRAMING BASICS
AND TIPS
User Input and Output in C++
Example: if (age > 18) { cout << "You are an adult."; } else { cout << "You are not an adult."; }
You can check multiple conditions with else if.
Example: if (age > 18) { cout << "Adult"; } else if (age > 12) { cout << "Teen"; } else { cout << "Child"; }
switch is used for multiple choices based on a single variable.
Example:
cpp
Copy code
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
default: cout << "Other day";
}
Example:
for (int i = 0; i < 5; i++)
{
cout << i;
}
i = 0 starts the loop.
i < 5 is the condition to keep running.
i++ increases i by 1 each time.
while loop runs while a condition is true.
Example:
while (i < 5)
{
cout << i;
i++;
}
i < 5 is the condition to keep running.
do-while loop runs at least once, then checks the condition.
Example:
cpp
Copy code
do {
cout << i;
i++;
} while (i < 5);
Example:
void greet()
{
cout << "Hello!";
}
Call a function with its name: greet();
Functions can take parameters (input).
Example:
void greet(string name)
{
cout << "Hello, " << name;
}
Call with a parameter: greet("Alice");
Functions can return a value.
Example:
cpp
Copy code
void printSum(int a, int b) {
int sum = a + b;
cout << "Sum: " << sum;
}
Access elements with an index: numbers[0] = 10; sets the first element.
Indexes start at 0.
Example: cout << numbers[0]; prints the first element.
Initialize with values: int numbers[5] = {1, 2, 3, 4, 5};