1. Flow Control
Flow control in C++ refers to the order in which statements are executed. It includes:
Conditional Statements:
if
,else if
,else
, andswitch
.Loops:
for
,while
, anddo-while
.Jump Statements:
break
,continue
, andreturn
.
Example:
int x = 10; if (x > 5) { cout << "x is greater than 5" << endl; } else { cout << "x is less than or equal to 5" << endl; }
2. Hello World
The classic "Hello World" program in C++:
#include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; return 0; }
3. Input From User in C++
To take input from the user, use cin
:
#include <iostream> using namespace std; int main() { int number; cout << "Enter a number: "; cin >> number; cout << "You entered: " << number << endl; return 0; }
4. Arithmetic Operators in C++
Arithmetic operators perform mathematical operations:
+
(addition)-
(subtraction)*
(multiplication)/
(division)%
(modulus)
Example:
int a = 10, b = 3; cout << "Sum: " << a + b << endl; cout << "Difference: " << a - b << endl; cout << "Product: " << a * b << endl; cout << "Quotient: " << a / b << endl; cout << "Remainder: " << a % b << endl;
5. Assignment Operators in C++
Assignment operators are used to assign values to variables:
=
(simple assignment)+=
,-=
,*=
,/=
,%=
(compound assignment)
Example:
int x = 5; x += 3; // Equivalent to x = x + 3 cout << "x: " << x << endl;
6. Comparison Operators in C++
Comparison operators compare two values:
==
(equal to)!=
(not equal to)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)
Example:
int a = 5, b = 10; if (a == b) { cout << "a and b are equal" << endl; } else { cout << "a and b are not equal" << endl; }
7. Logical Operators in C++
Logical operators are used to combine multiple conditions:
&&
(logical AND)||
(logical OR)!
(logical NOT)
Example:
int age = 20; bool isStudent = true; if (age >= 18 && isStudent) { cout << "You are an adult student." << endl; }
8. Math Functions in C++
C++ provides math functions in the <cmath>
library:
sqrt()
: Square rootpow()
: Powerabs()
: Absolute valuesin()
,cos()
,tan()
: Trigonometric functionslog()
,log10()
: Logarithmic functions
Example:
#include <iostream> #include <cmath> using namespace std; int main() { double num = 25.0; cout << "Square root: " << sqrt(num) << endl; cout << "2^3: " << pow(2, 3) << endl; return 0; }
Let me know if you need further clarification or examples!
0 Comments