Every C++ program follows a basic structure:
#include <iostream> // Preprocessor directive
using namespace std; // Namespace declaration
int main() { // Main function
// Program statements
return 0; // Return statement
}// or /* */Tokens are the smallest individual units in a C++ program:
int, float, double, char, boolif, else, for, while, doclass, struct, enum, voidreturn, break, continueNames given to variables, functions, classes, etc.
Rules for Identifiers:
Valid Examples:
myVariable, _count, studentName, PI_VALUEInvalid Examples:
2ndValue (starts with digit)my-variable (contains hyphen)class (reserved keyword)Fixed values in the program:
42, 0, -153.14, 2.5f, 1.23e-4'a', 'Z', '\n'"Hello World"true, falseSymbols that perform operations:
+, -, *, /, %==, !=, <, >, <=, >=&&, ||, !=, +=, -=, *=, /=Special symbols:
; (statement terminator){} (block delimiters)() (function calls, expressions)[] (array indexing), (separator)Instructions processed before compilation:
#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
#endifKey Points:
##include copies file content#define creates text substitutionStatements executed one after another in order.
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 (variable) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
break;
}for (initialization; condition; increment) {
// statements
}
// Example
for (int i = 0; i < 10; i++) {
cout << i << endl;
}while (condition) {
// statements
// update condition variable
}
// Example
int i = 0;
while (i < 10) {
cout << i << endl;
i++;
}do {
// statements
// update condition variable
} while (condition);
// Example
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 10);Exits the nearest enclosing loop or switch statement.
Skips the rest of the current loop iteration and jumps to the next iteration.
Exits from a function and optionally returns a value.
An array is a collection of elements of the same data type stored in contiguous memory locations.
// 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// 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;// 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 << " ";
}// 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 2Functions are reusable blocks of code that perform specific tasks.
return_type function_name(parameter_list) {
// function body
return value; // if return_type is not void
}// Declaration (prototype)
int add(int a, int b);
// Definition
int add(int a, int b) {
return a + b;
}// 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;
}void increment(int x) {
x++; // Original variable unchanged
}void increment(int& x) {
x++; // Original variable modified
}void increment(int* x) {
(*x)++; // Original variable modified
}Multiple functions with the same name but different parameters:
int max(int a, int b) {
return (a > b) ? a : b;
}
double max(double a, double b) {
return (a > b) ? a : b;
}// 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
}BEGIN
INPUT: Get user data
PROCESS: Perform calculations
OUTPUT: Display results
ENDTop-down analysis involves breaking a complex problem into smaller, manageable sub-problems.
Clearly define the overall problem and its requirements.
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 3Design each sub-problem as a separate module (function).
Combine all modules to solve the main problem.
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 summaryQuestion 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;?
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:
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).
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.
Question 9: Write a function that calculates the factorial of a number using recursion.
Question 10: Create overloaded functions named area() that calculate:
Question 11: Design a program using top-down analysis to manage a library system that can:
Break this down into modules and write the function prototypes.
Question 12: Write a complete program that:
_student_name - Valid2ndAttempt - Invalid (starts with digit)my-variable - Invalid (contains hyphen)class - Invalid (reserved keyword)PI_VALUE - Valid#include <iostream>
using namespace std;
int main() {
for (int i = 2; i <= 20; i += 2) {
cout << i << " ";
}
cout << endl;
return 0;
}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;
}int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}Remember: Programming is a skill that improves with practice. Don't be discouraged by initial difficulties – every programmer goes through the learning process!