Flow Control

1. Flow Control

Flow control in C++ refers to the order in which statements are executed. It includes:

  • Conditional Statementsifelse ifelse, and switch.

  • Loopsforwhile, and do-while.

  • Jump Statementsbreakcontinue, and return.

Example:

cpp
Copy
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++:

cpp
Copy
#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:

cpp
Copy
#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:

cpp
Copy
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:

cpp
Copy
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:

cpp
Copy
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:

cpp
Copy
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 root

  • pow(): Power

  • abs(): Absolute value

  • sin()cos()tan(): Trigonometric functions

  • log()log10(): Logarithmic functions

Example:

cpp
Copy
#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!

Post a Comment

0 Comments