Comprehensive Guide to Algorithms, C/C++ Data Types, Variables, Compilation Errors, Operators, and Control Statements

Algorithms and Flowcharts

  • An algorithm is a step-by-step procedure or a set of rules used to solve a specific problem. It is written in a structured manner using plain English or pseudocode.

Example Algorithm Problem: Sum of Two Numbers

  • Goal: Find the sum of two numbers.
  • Step-by-Step Procedure:
    1. Start
    2. Input two numbers: aa and bb
    3. Compute the sum: sum=a+b\text{sum} = a + b
    4. Display the sum
    5. Stop

Flowcharts

  • A flowchart is a visual representation of an algorithm using standard graphical symbols to illustrate the sequential flow of execution.
Flowchart Symbols
  • Terminator (Oval): Indicates the Start or End of a flowchart.
  • Parallelogram: Represents Input or Output operations (e.g., "Enter a number" or "Display result").
  • Rectangle: Represents a Process (e.g., arithmetic calculations).
  • Diamond: Represents a Decision-making step (e.g., "If X>YX > Y").
  • Arrow (➝): Represents a Flowline, indicating the direction and order of steps.
Flowchart Example: Sum of Two Numbers
  • Start (Oval)
  • \downarrow
  • Input a,ba, b (Parallelogram)
  • \downarrow
  • sum=a+b\text{sum} = a + b (Rectangle)
  • \downarrow
  • Display sum (Parallelogram)
  • \downarrow
  • Stop (Oval)

Pseudocode and Data Types in C and C++

  • Pseudocode is an informal, simplified way of writing an algorithm using a structured format that mimics programming logic without adhering to rigid syntax rules.

Pseudocode Example: Sum of Two Numbers

BEGIN
  INPUT a, b
  sum ← a + b
  PRINT sum
END

Data Types in C and C++

  • Data types specify the type of data that a variable can hold. In C and C++, data types are categorized into primary, derived, user-defined, type modifiers, and boolean types.
Primary (Basic) Data Types
  • Fundamental data types used to store simple values.
Data TypeSize (Bytes)Range
int22 or 4432,768-32,768 to 32,76732,767 (22 bytes) / 2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647 (44 bytes)
char11128-128 to 127127 or 00 to 255255
float443.4E383.4\text{E}-38 to 3.4E+383.4\text{E}+38 (66-77 decimal digits)
double881.7E3081.7\text{E}-308 to 1.7E+3081.7\text{E}+308 (1515-1616 decimal digits)
void00No value
Primary Data Types Example Code
#include <stdio.h> // Use <iostream> in C++

int main() {
  int num = 10;
  char letter = 'A';
  float pi = 3.14;
  double bigDecimal = 9.87654321;

  printf("Integer: %d\nCharacter: %c\nFloat: %f\nDouble: %lf\n", num, letter, pi, bigDecimal);
  return 0;
}
Derived Data Types
  • Data types constructed from fundamental primary data types.
Data TypeDescription
arrayCollection of elements of the same data type.
pointerStores memory address of another variable.
referenceAlias for an existing variable (C++ only).
functionSpecifies a function return type.
Derived Data Types Example Code
int arr[5] = {1, 2, 3, 4, 5}; // Array
int *ptr = &arr[0];           // Pointer
User-Defined Data Types
  • Custom data types defined by the programmer.
Data TypeDescription
structGroups variables of different data types into a single unit.
unionSimilar to struct, but all members share the same memory location.
enumDefines named integer constants.
classDefines objects containing data and methods (C++ only).
typedef / usingCreates an alias for an existing data type.
User-Defined Data Types Example Code
struct Person {
  char name[50];
  int age;
};

union Data {
  int i;
  float f;
};

enum Color { RED, GREEN, BLUE };
Type Modifiers (Qualifiers)
  • Keywords used to alter the memory size or sign property of basic data types.
ModifierDescription
signedStores both positive and negative values (default for int).
unsignedStores only positive values.
shortUses less memory than int.
longUses more memory than int.
Type Modifiers Example Code
unsigned int x = 100;    // Only positive values
long int y = 123456789;  // Bigger range than int
Boolean Data Type (C++ Only)
  • Includes a bool type to store truth values: true or false.
Boolean Example Code
bool isCodingFun = true;
Summary of Data Type Categories
CategoryData Types
Basicint, char, float, double, void
Derivedarray, pointer, reference, function
User-Definedstruct, union, enum, class, typedef
Modifierssigned, unsigned, short, long
Boolean (C++)bool

Variables, Scope, and Storage Classes in C

  • A variable in C is a named memory location used to store a value. The value stored in a variable can be modified during program execution.

Variable Declaration Syntax

  • Syntax without initialization: data_type variable_name;
  • Syntax with initialization: data_type variable_name = value;
Example Declarations
int age;         // Declaration
float pi = 3.14; // Initialization
char letter = 'A';

Rules for Naming Variables

  1. Can contain uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and underscores (_).
  2. Must begin with a letter or an underscore (e.g., _value, age).
  3. Cannot be a C keyword (e.g., int, return, etc.).
  4. Special characters are not allowed (e.g., @, $, %, -).
  5. Variable names are case-sensitive (age and Age are different variables).
Valid Variable Names
  • int student_age;
  • float _price;
  • char firstLetter;
Invalid Variable Names
  • int 3number; (Cannot start with a number)
  • float class; (class is a reserved keyword)
  • char first-name; (Hyphens are not allowed)

Types of Variables in C

  • Local Variable: Declared inside a function or block. Accessible only within that function/block.
  void function() {
    int x = 10; // Local variable
    printf("%d", x);
  }
&nbsp;&nbsp;```
- **Global Variable**: Declared outside all functions. Can be accessed from any function in the program.

c #include int globalVar = 100; // Global variable

void display() { printf("Global Variable: %d\n", globalVar); }

int main() { display(); return 0; }   ```

  • Static Variable: Retains its value between function calls. Automatically initialized to 00 if uninitialized.
  void counter() {
    static int count = 0; // Static variable
    count++;
    printf("%d ", count);
  }

  int main() {
    counter(); // Output: 1
    counter(); // Output: 2
    counter(); // Output: 3
    return 0;
  }
&nbsp;&nbsp;```
- **Extern Variable**: Declared using the `extern` keyword. Indicates that the variable is defined outside the current file or function scope.

c extern int x; // Defined elsewhere   ```

  • Register Variable: Stored in the CPU register instead of RAM for faster access. Declared using the register keyword. Its memory address cannot be accessed using the address-of operator &.
  void main() {
    register int speed = 50; // Stored in CPU register
  }
&nbsp;&nbsp;```

## Variable Scope Summary

| Scope Type | Description |
| :--- | :--- |
| Local | Exists inside a function/block only. |
| Global | Accessible throughout the program. |
| Static | Preserves its value between function calls. |
| Extern | Defined outside and used with `extern`. |

## Variable Storage Classes in C

| Storage Class | Scope | Lifetime | Default Value |
| :--- | :--- | :--- | :--- |
| `auto` (default) | Local | Function execution | Garbage |
| `static` | Local / Global | Program lifetime | 00 |
| `register` | Local | Function execution | Garbage |
| `extern` | Global | Program lifetime | 00 |

## Comprehensive Variable Types Example

c

include

// Global Variable int globalVar = 10;

void demo() { static int staticVar = 0; // Static Variable register int regVar = 5; // Register Variable staticVar++; printf("Static: %d, Register: %d\n", staticVar, regVar); }

int main() { int localVar = 20; // Local Variable extern int globalVar; // Extern Variable demo(); demo(); printf("Global: %d, Local: %d\n", globalVar, localVar); return 0; }

- **Output**:

text Static: 1, Register: 5 Static: 2, Register: 5 Global: 10, Local: 20   ```

Key Takeaways

  • Variables store values that can be changed during execution.
  • Naming rules: No special characters, no reserved keywords, strictly case-sensitive.
  • Types: Local, Global, Static, Extern, Register.
  • Storage classes: auto, static, register, extern.

Syntax Errors, Logical Errors, and Compilation Process

When compiling a C program, errors occur due to incorrect code structure or logical mistakes.

1. Syntax Errors

  • A syntax error occurs when code violates the structural rules of the C language.
  • The compiler detects syntax errors during compilation and stops the program from running.
Examples of Syntax Errors
  • Missing Semicolon (;):
  #include <stdio.h>
  int main() {
    printf("Hello, World!") // Missing semicolon
    return 0;
  }
&nbsp;&nbsp;```
  - *Corrected Code*:
    ```c
    printf("Hello, World!"); // Semicolon added
&nbsp;&nbsp;&nbsp;&nbsp;```
- **Incorrect Variable Declaration**:

c int 2num = 10; // Variable names cannot start with a number   ```

  • Corrected Code: c int num2 = 10; // Valid variable name &nbsp;&nbsp;&nbsp;&nbsp;
    • Mismatched Parentheses or Braces:
  #include <stdio.h>
  int main() {
    printf("Hello, World!"; // Missing closing parenthesis
    return 0;
  }
&nbsp;&nbsp;```
  - *Corrected Code*:
    ```c
    printf("Hello, World!"); // Fixed
&nbsp;&nbsp;&nbsp;&nbsp;```

### How to Fix Syntax Errors
- Carefully check spelling, punctuation, and syntax rules.
- Read compiler error messages and fix the highlighted lines.
- Use an IDE or code editor with syntax highlighting.

## 2. Logical Errors
- A **logical error** happens when the program compiles and runs without syntax errors, but produces incorrect results due to flaws in logic.

### Examples of Logical Errors
- **Incorrect Formula**:

c #include int main() { int a = 5, b = 10; int sum = a - b; // Logical error: Using subtraction instead of addition printf("Sum = %d\n", sum); // Output: -5 (Wrong result) return 0; }   ```

  • Corrected Code: c int sum = a + b; // Use addition instead &nbsp;&nbsp;&nbsp;&nbsp;
    • Incorrect Loop Condition (Infinite Loop):
  #include <stdio.h>
  int main() {
    int i = 1;
    while (i <= 5); { // Extra semicolon creates an infinite loop
      printf("%d ", i);
      i++; // Never executes
    }
    return 0;
  }
&nbsp;&nbsp;```
  - *Corrected Code*:
    ```c
    while (i <= 5) { // No semicolon
      printf("%d ", i);
      i++;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

### How to Fix Logical Errors
- Use print statements (`printf`) to debug and trace variable values.
- Run the program with different test cases.
- Analyze the logic carefully before writing code.

## 3. Compilation and Execution Process
- **Compilation Steps in C**:
  1. **Preprocessing (`.c` file)**: Handles `#include`, `#define`, and macros.
  2. **Compilation (`.i` file)**: Converts code into Assembly language.
  3. **Assembly (`.s` file)**: Converts Assembly code to machine code.
  4. **Linking (`.o` file)**: Links function calls (such as `printf()`) to the standard library.
  5. **Execution**: Runs the final machine code.

### Example of Compilation in GCC

bash gcc program.c -o program ./program

## Summary Comparison of Errors

| Error Type | Detected By | Effect |
| :--- | :--- | :--- |
| Syntax Error | Compiler | Stops program from running |
| Logical Error | Programmer | Produces incorrect results |


# Arithmetic Expressions and Operator Precedence in C and C++

Arithmetic expressions in C and C++ are formed using arithmetic operators and operands. The evaluation order is dictated by operator precedence and associativity.

## 1. Arithmetic Operators

| Operator | Symbol | Example | Description |
| :--- | :--- | :--- | :--- |
| Addition | `+` | `a + b` | Adds two numbers |
| Subtraction | `-` | `a - b` | Subtracts second number from first |
| Multiplication | `*` | `a * b` | Multiplies two numbers |
| Division | `/` | `a / b` | Divides first number by second |
| Modulus | `%` | `a % b` | Returns remainder of division |

## 2. Arithmetic Expression Examples

### Example 1: Basic Arithmetic Operations

c

include

int main() { int a = 10, b = 5;

printf("Addition: %d\n", a + b); printf("Subtraction: %d\n", a - b); printf("Multiplication: %d\n", a * b); printf("Division: %d\n", a / b); printf("Modulus: %d\n", a % b); return 0; }

- **Output**:

text Addition: 15 Subtraction: 5 Multiplication: 50 Division: 2 Modulus: 0   ```

Example 2: Expression Evaluation
#include <stdio.h>

int main() {
  int x = 5, y = 2, result;
  result = x + y * 3 - 4 / 2; // 5 + (2 * 3) - (4 / 2)
  printf("Result: %d\n", result); // Output: 9
  return 0;
}

3. Operator Precedence Table

PrecedenceOperatorDescriptionAssociativity
11 (Highest)(), [], ->, .Parentheses, Array, Member AccessLeft to Right
22++, --, +, -, !, ~Unary OperatorsRight to Left
33*, /, %Multiplication, Division, ModulusLeft to Right
44+, -Addition, SubtractionLeft to Right
55<<, >>Bitwise ShiftLeft to Right
66<, <=, >, >=Relational OperatorsLeft to Right
77==, !=Equality OperatorsLeft to Right
88&Bitwise ANDLeft to Right
99^Bitwise XORLeft to Right
1010|Bitwise ORLeft to Right
1111&&Logical ANDLeft to Right
1212||Logical ORLeft to Right
1313? :Ternary OperatorRight to Left
1414=, +=, -=, *=, /=, %=Assignment OperatorsRight to Left
1515 (Lowest),Comma OperatorLeft to Right

4. Operator Precedence Examples

Example 1: Precedence without Parentheses
#include <stdio.h>

int main() {
  int result = 10 + 2 * 5; // Multiplication (*) is performed first
  printf("Result: %d\n", result); // Output: 20
  return 0;
}
Example 2: Using Parentheses to Change Precedence
#include <stdio.h>

int main() {
  int result = (10 + 2) * 5; // Parentheses change order
  printf("Result: %d\n", result); // Output: 60
  return 0;
}

5. Associativity of Operators

  • If two operators share the same precedence, associativity decides the order of evaluation.
  • Left to Right Associativity Example: a - b + c is evaluated as (a - b) + c.
  • Right to Left Associativity Example: a = b = c is evaluated as a = (b = c).
Code Example of Associativity
#include <stdio.h>

int main() {
  int x = 10;
  int y = 20;
  int result = x - y + 5; // Left to Right: (10 - 20) + 5
  printf("Result: %d\n", result); // Output: -5
  return 0;
}

6. Special Cases in Arithmetic

Division in Integer Arithmetic
  • Performing division with two integers yields an integer result:
  int result = 5 / 2; // Result is 2, not 2.5
&nbsp;&nbsp;```
- To obtain a floating-point result, use floating-point literals:

c float result = 5.0 / 2; // Result is 2.5   ```

Modulus Operator (%) Restrictions
  • Modulus only works with integers:
  int result = 10 % 3; // Result: 1
&nbsp;&nbsp;```
- **Incorrect Usage**:

c float result = 10.5 % 3.2; // ERROR: Modulus operator doesn't work with float/double   ```

7. Arithmetic Summary

  • Arithmetic Operators: +, -, *, /, %
  • Precedence: * / % > + -
  • Use parentheses to explicitly define evaluation order.
  • Associativity: Left to Right (except for unary, ternary, and assignment operators).

Conditional, Branching, and Looping Statements in C and C++

In C and C++, conditional and looping statements control execution flow based on conditions.

1. Conditional Statements (Decision Making)

1.1 if Statement
  • Executes a block of code only if the condition is true.
  • Syntax:
  if (condition) {
    // Code to execute if condition is true
  }
&nbsp;&nbsp;```
- **Example**:

c #include

int main() { int num = 10; if (num > 5) { printf("Number is greater than 5\n"); } return 0; }   ```

1.2 if-else Statement
  • Executes one block if condition is true; otherwise executes the else block.
  • Syntax:
  if (condition) {
    // Code if condition is true
  } else {
    // Code if condition is false
  }
&nbsp;&nbsp;```
- **Example**:

c #include

int main() { int num = 3; if (num > 5) { printf("Number is greater than 5\n"); } else { printf("Number is less than or equal to 5\n"); } return 0; }   ```

1.3 if-else if-else Ladder
  • Used when evaluating multiple conditions sequentially.
  • Syntax:
  if (condition1) {
    // Code for condition1
  } else if (condition2) {
    // Code for condition2
  } else {
    // Code if none of the conditions are true
  }
&nbsp;&nbsp;```
- **Example**:

c #include

int main() { int num = 0; if (num > 0) { printf("Positive Number\n"); } else if (num < 0) { printf("Negative Number\n"); } else { printf("Zero\n"); } return 0; }   ```

1.4 Nested if Statement
  • An if statement nested inside another if statement.
  • Example:
  #include <stdio.h>

  int main() {
    int num = 20;
    if (num > 10) {
      if (num < 30) {
        printf("Number is between 10 and 30\n");
      }
    }
    return 0;
  }
&nbsp;&nbsp;```

### 1.5 `switch` Statement
- Used to replace multiple `if-else` conditions when checking for equality against discrete constants.
- **Syntax**:

c switch (expression) { case value1: // Code for case 1 break; case value2: // Code for case 2 break; default: // Code if no cases match }   ```

  • Example:
  #include <stdio.h>

  int main() {
    int day = 3;
    switch (day) {
      case 1:
        printf("Monday\n");
        break;
      case 2:
        printf("Tuesday\n");
        break;
      case 3:
        printf("Wednesday\n");
        break;
      default:
        printf("Invalid day\n");
    }
    return 0;
  }
&nbsp;&nbsp;```

## 2. Looping Statements

### 2.1 `for` Loop
- Used when the exact number of iterations is known.
- **Syntax**:

c for (initialization; condition; update) { // Code to execute }   ```

  • Example:
  #include <stdio.h>

  int main() {
    for (int i = 1; i <= 5; i++) {
      printf("%d ", i);
    }
    return 0;
  }
&nbsp;&nbsp;```
- **Output**: `1 2 3 4 5`

### 2.2 `while` Loop
- Executes repeatedly as long as the condition remains true.
- **Syntax**:

c while (condition) { // Code to execute }   ```

  • Example:
  #include <stdio.h>

  int main() {
    int i = 1;
    while (i <= 5) {
      printf("%d ", i);
      i++;
    }
    return 0;
  }
&nbsp;&nbsp;```

### 2.3 `do-while` Loop
- Similar to `while`, but guarantees block execution at least once before testing the condition.
- **Syntax**:

c do { // Code to execute } while (condition);   ```

  • Example:
  #include <stdio.h>

  int main() {
    int i = 1;
    do {
      printf("%d ", i);
      i++;
    } while (i <= 5);
    return 0;
  }
&nbsp;&nbsp;```

## 3. Jump Statements (Branching)

### 3.1 `break` Statement
- Exits the innermost loop or switch block immediately.
- **Example**:

c #include

int main() { for (int i = 1; i <= 5; i++) { if (i == 3) { break; // Stops at 3 } printf("%d ", i); } return 0; }   ```

  • Output: 1 2
3.2 continue Statement
  • Skips the rest of the current loop iteration and moves to the next pass.
  • Example:
  #include <stdio.h>

  int main() {
    for (int i = 1; i <= 5; i++) {
      if (i == 3) {
        continue; // Skips 3
      }
      printf("%d ", i);
    }
    return 0;
  }
&nbsp;&nbsp;```
- **Output**: `1 2 4 5`

### 3.3 `goto` Statement (Not Recommended)
- Unconditionally jumps to a specified labeled section.
- **Example**:

c #include

int main() { int num = 3; if (num == 3) { goto skip; } printf("This won't print\n"); skip: printf("Jumped to label\n"); return 0; }   ```

4. Control Statements Summary Table

Statement TypeUsed For
if-elseDecision making
switchMultiple choices
forFixed number of iterations
whileLoop until condition is false
do-whileAt least one execution, then loop
breakExits loop early
continueSkips iteration
gotoUnstructured jump (avoid using)