Content is user-generated and unverified.

C++ Fundamentals Study Guide

Table of Contents

  1. Basic C++ Elements
  2. Tokens, Preprocessor Directives, Identifiers
  3. Control Structures
  4. Array Implementation
  5. Creating Your Own Functions
  6. Problem Solving Skills
  7. Top-Down Analysis
  8. Practice Questions

Basic C++ Elements

Program Structure

Every C++ program follows a basic structure:

cpp
#include <iostream>    // Preprocessor directive
using namespace std;   // Namespace declaration

int main() {          // Main function
    // Program statements
    return 0;         // Return statement
}

Key Components:

  • Headers: Files containing function declarations and definitions
  • Main function: Entry point of every C++ program
  • Statements: Individual instructions ending with semicolons
  • Comments: Documentation using // or /* */

Tokens, Preprocessor Directives, Identifiers

Tokens

Tokens are the smallest individual units in a C++ program:

1. Keywords (Reserved Words)

  • int, float, double, char, bool
  • if, else, for, while, do
  • class, struct, enum, void
  • return, break, continue

2. Identifiers

Names given to variables, functions, classes, etc.

Rules for Identifiers:

  • Must start with a letter (a-z, A-Z) or underscore (_)
  • Can contain letters, digits (0-9), and underscores
  • Cannot be a reserved keyword
  • Case-sensitive
  • No spaces allowed

Valid Examples:

  • myVariable, _count, studentName, PI_VALUE

Invalid Examples:

  • 2ndValue (starts with digit)
  • my-variable (contains hyphen)
  • class (reserved keyword)

3. Literals

Fixed values in the program:

  • Integer literals: 42, 0, -15
  • Floating-point literals: 3.14, 2.5f, 1.23e-4
  • Character literals: 'a', 'Z', '\n'
  • String literals: "Hello World"
  • Boolean literals: true, false

4. Operators

Symbols that perform operations:

  • Arithmetic: +, -, *, /, %
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: &&, ||, !
  • Assignment: =, +=, -=, *=, /=

5. Punctuators

Special symbols:

  • ; (statement terminator)
  • {} (block delimiters)
  • () (function calls, expressions)
  • [] (array indexing)
  • , (separator)

Preprocessor Directives

Instructions processed before compilation:

Common Directives:

cpp
#include <iostream>     // Include system header
#include "myheader.h"   // Include user-defined header
#define PI 3.14159      // Define constant
#define MAX(a,b) ((a)>(b)?(a):(b))  // Define macro
#ifdef DEBUG            // Conditional compilation
#endif

Key Points:

  • Begin with #
  • Processed before compilation
  • No semicolon needed
  • #include copies file content
  • #define creates text substitution

Control Structures

1. Sequential Structure

Statements executed one after another in order.

2. Selection Structures

If-Else Statement

cpp
if (condition) {
    // statements executed if condition is true
} else if (another_condition) {
    // statements executed if another_condition is true
} else {
    // statements executed if all conditions are false
}

Switch Statement

cpp
switch (variable) {
    case value1:
        // statements
        break;
    case value2:
        // statements
        break;
    default:
        // statements
        break;
}

3. Repetition Structures

For Loop

cpp
for (initialization; condition; increment) {
    // statements
}

// Example
for (int i = 0; i < 10; i++) {
    cout << i << endl;
}

While Loop

cpp
while (condition) {
    // statements
    // update condition variable
}

// Example
int i = 0;
while (i < 10) {
    cout << i << endl;
    i++;
}

Do-While Loop

cpp
do {
    // statements
    // update condition variable
} while (condition);

// Example
int i = 0;
do {
    cout << i << endl;
    i++;
} while (i < 10);

4. Jump Statements

Break

Exits the nearest enclosing loop or switch statement.

Continue

Skips the rest of the current loop iteration and jumps to the next iteration.

Return

Exits from a function and optionally returns a value.


Array Implementation

Array Basics

An array is a collection of elements of the same data type stored in contiguous memory locations.

Declaration and Initialization

cpp
// Declaration
int numbers[5];                    // Array of 5 integers
double grades[100];                // Array of 100 doubles

// Declaration with initialization
int scores[5] = {85, 92, 78, 96, 88};
int values[] = {1, 2, 3, 4, 5};    // Size determined automatically
int data[10] = {0};                // Initialize all elements to 0

Array Access

cpp
// Accessing elements (0-based indexing)
scores[0] = 85;    // First element
scores[4] = 88;    // Last element (for array of size 5)

// Reading elements
cout << "First score: " << scores[0] << endl;

Array Processing

cpp
// Processing all elements
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += scores[i];
}

// Using range-based for loop (C++11)
for (int score : scores) {
    cout << score << " ";
}

Multi-dimensional Arrays

cpp
// 2D array declaration
int matrix[3][4];    // 3 rows, 4 columns

// 2D array initialization
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};

// Accessing 2D array elements
matrix[1][2] = 10;   // Row 1, Column 2

Array Limitations

  • Fixed size at compile time
  • No bounds checking
  • Cannot be assigned directly
  • Size not stored with the array

Creating Your Own Functions

Function Basics

Functions are reusable blocks of code that perform specific tasks.

Function Anatomy

cpp
return_type function_name(parameter_list) {
    // function body
    return value;  // if return_type is not void
}

Function Declaration vs Definition

cpp
// Declaration (prototype)
int add(int a, int b);

// Definition
int add(int a, int b) {
    return a + b;
}

Function Examples

cpp
// Function with no parameters
void greet() {
    cout << "Hello World!" << endl;
}

// Function with parameters
int multiply(int x, int y) {
    return x * y;
}

// Function with default parameters
void printMessage(string msg = "Default message") {
    cout << msg << endl;
}

Parameter Passing

Pass by Value

cpp
void increment(int x) {
    x++;  // Original variable unchanged
}

Pass by Reference

cpp
void increment(int& x) {
    x++;  // Original variable modified
}

Pass by Pointer

cpp
void increment(int* x) {
    (*x)++;  // Original variable modified
}

Function Overloading

Multiple functions with the same name but different parameters:

cpp
int max(int a, int b) {
    return (a > b) ? a : b;
}

double max(double a, double b) {
    return (a > b) ? a : b;
}

Arrays and Functions

cpp
// Function receiving array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

// Alternative syntax
void printArray(int* arr, int size) {
    // Same implementation
}

Problem Solving Skills

1. Understanding the Problem

  • Read the problem carefully
  • Identify what is given (input)
  • Identify what needs to be found (output)
  • Identify any constraints or special conditions

2. Planning the Solution

  • Break down the problem into smaller sub-problems
  • Identify the algorithm or approach
  • Consider edge cases and error conditions
  • Plan the data structures needed

3. Algorithm Design Techniques

Pseudocode

BEGIN
    INPUT: Get user data
    PROCESS: Perform calculations
    OUTPUT: Display results
END

Flowchart Elements

  • Oval: Start/End
  • Rectangle: Process/Action
  • Diamond: Decision
  • Parallelogram: Input/Output

4. Implementation Strategy

  • Start with a simple version
  • Test with sample data
  • Add features incrementally
  • Handle edge cases
  • Optimize if necessary

Top-Down Analysis

Methodology

Top-down analysis involves breaking a complex problem into smaller, manageable sub-problems.

Steps in Top-Down Design

1. Main Problem Definition

Clearly define the overall problem and its requirements.

2. Problem Decomposition

Break the main problem into smaller sub-problems:

Main Problem
├── Sub-problem 1
│   ├── Sub-sub-problem 1.1
│   └── Sub-sub-problem 1.2
├── Sub-problem 2
└── Sub-problem 3

3. Module Design

Design each sub-problem as a separate module (function).

4. Integration

Combine all modules to solve the main problem.

Example: Student Grade Management System

Main Problem: Manage student grades
├── Input Module
│   ├── Read student names
│   └── Read test scores
├── Processing Module
│   ├── Calculate individual averages
│   ├── Find class average
│   └── Determine letter grades
└── Output Module
    ├── Display individual reports
    └── Display class summary

Benefits of Top-Down Analysis

  • Easier to understand and manage
  • Promotes code reusability
  • Simplifies debugging and testing
  • Enables team collaboration
  • Reduces complexity

Practice Questions

Section 1: Tokens and Identifiers

Question 1: Which of the following are valid C++ identifiers? a) _student_name b) 2ndAttempt c) my-variable d) class e) PI_VALUE

Question 2: What is the difference between #define PI 3.14159 and const double PI = 3.14159;?

Section 2: Control Structures

Question 3: Write a program that prints all even numbers from 2 to 20 using a for loop.

Question 4: Convert the following for loop to a while loop:

cpp
for (int i = 10; i >= 1; i--) {
    cout << i << " ";
}

Question 5: Write a switch statement that converts a numerical grade (0-100) to a letter grade (A, B, C, D, F).

Section 3: Arrays

Question 6: Write a function that finds the maximum element in an array of integers.

Question 7: Create a program that reverses an array in-place (without using additional arrays).

Question 8: Write a function that checks if an array is sorted in ascending order.

Section 4: Functions

Question 9: Write a function that calculates the factorial of a number using recursion.

Question 10: Create overloaded functions named area() that calculate:

  • Area of a square (one parameter)
  • Area of a rectangle (two parameters)
  • Area of a circle (one parameter, use PI = 3.14159)

Section 5: Problem Solving

Question 11: Design a program using top-down analysis to manage a library system that can:

  • Add new books
  • Search for books by title or author
  • Check out books
  • Return books
  • Display available books

Break this down into modules and write the function prototypes.

Question 12: Write a complete program that:

  • Reads student names and three test scores for each student
  • Calculates the average for each student
  • Determines and displays the class average
  • Finds and displays the student with the highest average

Sample Solutions

Solution 1: Valid Identifiers

  • a) _student_name - Valid
  • b) 2ndAttempt - Invalid (starts with digit)
  • c) my-variable - Invalid (contains hyphen)
  • d) class - Invalid (reserved keyword)
  • e) PI_VALUE - Valid

Solution 3: Even Numbers

cpp
#include <iostream>
using namespace std;

int main() {
    for (int i = 2; i <= 20; i += 2) {
        cout << i << " ";
    }
    cout << endl;
    return 0;
}

Solution 6: Maximum Element

cpp
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

Solution 9: Factorial (Recursive)

cpp
int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

Study Tips

  1. Practice Regularly: Write code daily to reinforce concepts
  2. Understand, Don't Memorize: Focus on understanding the logic
  3. Debug Systematically: Use print statements and debuggers
  4. Test Edge Cases: Test with boundary values and special cases
  5. Code Review: Read and understand others' code
  6. Start Simple: Begin with basic programs and gradually increase complexity
  7. Use Comments: Document your code for better understanding
  8. Learn from Errors: Analyze compilation and runtime errors

Remember: Programming is a skill that improves with practice. Don't be discouraged by initial difficulties – every programmer goes through the learning process!

Content is user-generated and unverified.
    C++ Fundamentals Study Guide | Claude