C++ Programming Fundamentals: Structure, Data Types, and Control Flow
C++ Program Structure Essentials
A C++ program has a fixed structure that every code must follow. It starts with header files, then the main function, and ends properly. This makes the code organized and error-free. Let me explain each part step by step.
1. Header Files (Preprocessor Directives)
These come first using #include statements. They bring in library functions like iostream for input/output. Example: #include <iostream>. Without them, you can’t use cout or cin.
2. Namespace
We use using namespace std; to avoid writing std:: every time for standard functions. It simplifies code.
3. Main Function
This is the heart of the program. Every C++ program starts from int main() { }. Code inside runs here. It returns 0 to show successful execution.
4. Body of Main
Contains statements, variables, loops, etc. Ends with a return statement.
5. Closing Brace
All blocks end with }.
Simple C++ Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}Data Types Used in C++
In C++, we use different types of data to store information. These are called data types. They tell the computer how much memory to use and what kind of value it can hold, like numbers, letters, or decisions (true/false). Main data types are divided into basic and derived types.
Basic Data Types (Primitive Types)
These are the building blocks:
int: Stores whole numbers (integers) without decimals. Example:int age = 20;(typically uses 4 bytes).float: Stores decimal numbers with single precision. Example:float marks = 85.5;(uses 4 bytes).double: Stores decimal numbers with double precision (more accurate). Example:double pi = 3.14159;(uses 8 bytes).char: Stores single characters or letters. Example:char grade = 'A';(uses 1 byte).void: Means no value (used in functions). Example:void display();.
Derived Data Types
Built from basic types:
- Array: Group of same data type. Example:
int arr[5] = {10,20,30};. - Pointer: Stores memory address. Example:
int *p;. - Structure: Group of different data types. Example:
struct student { char name[20]; int roll; };.
These data types help in efficient memory use. For example, use int for counts, float for prices.
The while Loop in C++
A while loop in C++ programming repeats a block of code as long as a given condition stays true. It first checks the condition, and if true, executes the code inside. This repeats until the condition becomes false.
Syntax:
while (condition) {
// code to repeat
}How it works (step-by-step):
- Check the condition.
- If true, run the code block.
- Go back to step 1.
- Stop when condition is false.
Example: Print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1; // Start with 1
while (i <= 5) { // Condition: i less than or equal to 5
cout << i << " "; // Print current number
i++; // Increase i by 1
}
return 0;
}Key points:
- Always update the variable (like
i++) inside, or it causes an infinite loop (endless repeat). - Good for unknown repeat counts, unlike the
for-loop.
C++ switch-case Statement
A switch-case statement in C++ is a simple way to choose one block of code from many options based on a single value. It works like a menu where you pick one option and run only that part. This makes your code cleaner than using many if-else statements, especially for exact matches like numbers or characters.
Example: Day of the Week Selector
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter day number (1-7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Wrong day number!" << endl;
}
return 0;
}Functions in C Programming
In C programming, a function is a named block of code that performs a specific task. It is like a small program inside your main program. You write the code once in a function and call (use) it multiple times from anywhere, avoiding repetition.
Functions make code organized, reusable, and easy to debug. Every C program has at least one function: main().
Syntax to declare a function:
return_type function_name(parameters) {
// function body (code)
return value; // optional
}Example (Addition Function):
#include <stdio.h>
// Function definition
int add(int a, int b) {
return a + b; // function body
}
int main() {
int result = add(5, 3); // calling function
printf("Sum: %d", result); // Output: Sum: 8
return 0;
}What is an Array?
An array is a collection of similar data items stored in consecutive memory locations. It allows us to store multiple values of the same type under a single name. Each item in the array is accessed using an index, starting from 0.
For example, if we declare an array marks[5], it can hold 5 integer values. Arrays make it easy to handle lists of data efficiently.
Program to Enter and Display 10 Elements of an Array (Java Example)
Here’s a simple Java program that takes 10 integer elements from the user and displays them:
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
int[] arr = new int[10]; // Declare array of size 10
Scanner sc = new Scanner(System.in);
// Enter 10 elements
System.out.println("Enter 10 elements:");
for(int i = 0; i < 10; i++) {
arr[i] = sc.nextInt();
}
// Display 10 elements
System.out.println("Array elements are:");
for(int i = 0; i < 10; i++) {
System.out.print(arr[i] + " ");
}
sc.close();
}
}
Sample Output:
Enter 10 elements:
10 20 30 40 50 60 70 80 90 100
Array elements are:
10 20 30 40 50 60 70 80 90 100Variables, Constants, and Operators
Variables
A variable is a named storage location in memory that holds a value, which can change during program execution. We declare it with a data type like int age = 20;. It acts like a box where you store and update data easily.
Constants
Constants are fixed values that cannot change once defined. Use const int MAX = 100; or #define PI 3.14. They are useful for values like PI or maximum size to avoid accidental changes.
Two Input and Output Functions (C Style)
printf(): Outputs data to screen, e.g.,printf("Hello %d", 10);prints “Hello 10”.scanf(): Inputs data from user, e.g.,scanf("%d", &num);reads an integer into variablenum.
Unary Operators
Unary operators work on a single operand. Examples:
++or--(increment/decrement, e.g.,x++increases x by 1).!(logical not),&(address),*(pointer dereference). They change or access one value directly.
Keywords
Keywords are reserved words with special meaning in C/C++, like int, if, while, return. You cannot use them as variable names (e.g., don’t name a variable for). There are 32 keywords in standard C.
getch() Function
getch() is from the <conio.h> header (often used in older C compilers). It reads a character from the keyboard without showing it on screen or waiting for the Enter key. Example: char c = getch();. Useful for menus or games to pause execution without echoing input.
