Basic Components of a C++ Program
A C++ program consists of one or more function modules, with each function being an independent code unit that accomplishes a specific task. Understanding the basic structure of a C++ program is the first step in learning this language.
Basic Structure of a Function
main() Function – Program Entry Point
#include <iostream> // Include input-output header file
// main() function is the entry point of every C++ program
int main() { // Function header
// Function body starts
std::cout << "Hello, World!" << std::endl;
return 0; // Return statement
} // Function body ends
Detailed Breakdown of Functions
#include <iostream>
using namespace std;
// Function prototype: declares the return type and parameters of the function
double calculateArea(double radius); // Return type: double, parameter: double
int main() {
// Declaration statement: defining variables
double circleRadius;
double area;
// Message statement: sending a message to cout object
cout << "Please enter the radius of the circle: ";
// Message statement: getting input from cin object
cin >> circleRadius;
// Function call: executing calculateArea function
area = calculateArea(circleRadius);
// Message statement: outputting the result
cout << "The area of the circle is: " << area << endl;
// Return statement: returning value from main function
return 0;
}
// Function definition
double calculateArea(double radius) { // Function header
// Function body starts
const double PI = 3.14159; // Declaration statement
double result; // Declaration statement
// Assignment statement: assigning value to variable
result = PI * radius * radius;
// Return statement: returning the calculated result to the caller
return result;
} // Function body ends
Six Types of C++ Statements Explained
1. Declaration Statements
#include <iostream>
#include <string>
using namespace std;
int main() {
// Basic data type declarations
int age; // Declare integer variable
double salary = 5000.75; // Declare and initialize
char grade = 'A'; // Declare character variable
bool isActive = true; // Declare boolean variable
// String declaration
string name = "Zhang San";
// Constant declaration
const int MAX_SCORE = 100;
const double TAX_RATE = 0.08;
// Array declaration
int scores[5] = {85, 92, 78, 88, 95};
// Pointer declaration
int* pointerToAge = &age;
cout << "Name: " << name << endl;
cout << "Max Score: " << MAX_SCORE << endl;
return 0;
}
2. Assignment Statements
#include <iostream>
using namespace std;
int main() {
// Simple assignment
int x = 10;
int y = 20;
// Arithmetic operation assignment
x = x + 5; // Traditional way
x += 5; // Compound assignment
y *= 2; // Equivalent to y = y * 2
// Multiple assignment
int a, b, c;
a = b = c = 100; // All three variables assigned 100
// Expression assignment
double result = (x + y) * 2.5;
// Increment and decrement assignment
int counter = 0;
counter++; // Post-increment
++counter; // Pre-increment
counter--; // Post-decrement
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "result = " << result << endl;
cout << "counter = " << counter << endl;
return 0;
}
3. Message Statements
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
public:
Student(string n, int a) : name(n), age(a) {}
// Member function: messages that the object can receive
void displayInfo() {
cout << "Student Name: " << name << ", Age: " << age << endl;
}
void setName(string newName) {
name = newName;
}
void setAge(int newAge) {
age = newAge;
}
};
int main() {
// Create object
Student student1("Li Si", 20);
// Message statement: sending message to object
student1.displayInfo(); // Sending displayInfo message
// Sending messages to modify attributes
student1.setName("Wang Wu");
student1.setAge(21);
student1.displayInfo();
// Standard input-output object messages
string input;
cout << "Please enter your name: "; // Sending insert message to cout
cin >> input; // Sending extract message to cin
cout << "Hello, " << input << "!" << endl;
return 0;
}
4. Function Calls
#include <iostream>
#include <cmath> // Include math functions
using namespace std;
// Function prototypes
int add(int a, int b);
double calculateCircleArea(double radius);
void printWelcomeMessage(string name);
int factorial(int n);
int main() {
// Function call: using return value
int sum = add(15, 25);
cout << "15 + 25 = " << sum << endl;
// Function call: directly used in expression
double area = calculateCircleArea(5.0);
cout << "Area of circle with radius 5: " << area << endl;
// Function call: not concerned with return value
printWelcomeMessage("Zhang San");
// Library function call
double root = sqrt(64.0);
double power = pow(2.0, 8.0);
cout << "Square root of 64: " << root << endl;
cout << "2 raised to the power of 8: " << power << endl;
// Recursive function call
int fact = factorial(5);
cout << "Factorial of 5: " << fact << endl;
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
double calculateCircleArea(double radius) {
return 3.14159 * radius * radius;
}
void printWelcomeMessage(string name) {
cout << "Welcome, " << name << "!" << endl;
}
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1); // Recursive call
}
5. Function Prototypes
#include <iostream>
#include <string>
using namespace std;
// Function prototype declarations
// Informing the compiler of the function's existence without implementation
double calculateBMI(double weight, double height);
string getHealthStatus(double bmi);
void displayResults(string name, double bmi, string status);
int findMax(int a, int b, int c);
bool isValidAge(int age);
int main() {
string userName;
double weight, height;
int age;
cout << "Please enter your name: ";
cin >> userName;
cout << "Please enter your age: ";
cin >> age;
if (isValidAge(age)) {
cout << "Please enter weight (kg): ";
cin >> weight;
cout << "Please enter height (m): ";
cin >> height;
double bmi = calculateBMI(weight, height);
string status = getHealthStatus(bmi);
displayResults(userName, bmi, status);
} else {
cout << "Invalid age!" << endl;
}
// Using multi-parameter function
int maxValue = findMax(15, 8, 22);
cout << "Max value among 15, 8, 22: " << maxValue << endl;
return 0;
}
// Function definitions - implementing previously declared functions
double calculateBMI(double weight, double height) {
return weight / (height * height);
}
string getHealthStatus(double bmi) {
if (bmi < 18.5) return "Underweight";
else if (bmi < 24) return "Normal weight";
else if (bmi < 28) return "Overweight";
else return "Obesity";
}
void displayResults(string name, double bmi, string status) {
cout << "\n=== Health Report ===" << endl;
cout << "Name: " << name << endl;
cout << "BMI Index: " << bmi << endl;
cout << "Health Status: " << status << endl;
cout << "================" << endl;
}
int findMax(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}
bool isValidAge(int age) {
return (age > 0 && age < 150);
}
6. Return Statements
#include <iostream>
#include <string>
using namespace std;
// Functions returning different data types
int getInteger() {
return 42; // Return integer literal
}
double calculateAverage(int a, int b, int c) {
double avg = (a + b + c) / 3.0;
return avg; // Return variable value
}
string getGreeting(string name) {
return "Hello, " + name + "!"; // Return expression result
}
bool isEven(int number) {
return (number % 2 == 0); // Return boolean expression
}
// Early return example
string getGrade(int score) {
if (score < 0 || score > 100) {
return "Invalid score"; // Early return
}
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F"; // Final return
}
// void function with return
void processNumber(int num) {
if (num < 0) {
cout << "Number cannot be negative!" << endl;
return; // Early exit from function, no return value
}
cout << "Processing number: " << num << endl;
// Implicit return, no return statement needed
}
int main() {
// Testing various return types
cout << "Integer: " << getInteger() << endl;
cout << "Average: " << calculateAverage(10, 20, 30) << endl;
cout << "Greeting: " << getGreeting("World") << endl;
cout << "Is 15 even: " << (isEven(15) ? "Yes" : "No") << endl;
cout << "Grade for 85: " << getGrade(85) << endl;
processNumber(10);
processNumber(-5);
return 0; // Return from main function
}
Concepts of Classes and Objects
#include <iostream>
#include <string>
using namespace std;
// Class definition: user-defined data type specification
class BankAccount {
private:
// Data members: describe how to represent information
string accountHolder;
string accountNumber;
double balance;
public:
// Constructor
BankAccount(string holder, string number, double initialBalance) {
accountHolder = holder;
accountNumber = number;
balance = initialBalance;
}
// Member function: operations that can be performed on data
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Successfully deposited: $" << amount << endl;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Successfully withdrew: $" << amount << endl;
return true;
}
cout << "Withdrawal failed: Insufficient balance" << endl;
return false;
}
void displayInfo() {
cout << "Account Holder: " << accountHolder << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Current Balance: $" << balance << endl;
}
double getBalance() {
return balance;
}
};
int main() {
// Object creation: entity created based on class specification
BankAccount myAccount("Zhang San", "123456789", 1000.0); // Create object
// Using object
myAccount.displayInfo();
myAccount.deposit(500.0);
myAccount.withdraw(200.0);
myAccount.displayInfo();
// Create another object
BankAccount anotherAccount("Li Si", "987654321", 500.0);
anotherAccount.displayInfo();
return 0;
}
Input and Output Objects: cin and cout
#include <iostream>
#include <string>
using namespace std;
int main() {
// cout object: instance of ostream class
// << insertion operator: inserts data into output stream
// Basic output
cout << "Welcome to the C++ Input-Output demonstration" << endl;
// Output various data types
int age = 25;
double salary = 5000.75;
char grade = 'A';
bool isEmployed = true;
string name = "Wang Wu";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
cout << "Grade: " << grade << endl;
cout << "Employed: " << isEmployed << endl;
// Formatted output
cout << "Salary (formatted): $" << fixed << salary << endl;
// cin object: instance of istream class
// >> extraction operator: extracts information from input stream
string userName;
int userAge;
double userSalary;
cout << "\nPlease enter your name: ";
cin >> userName; // Extract string
cout << "Please enter your age: ";
cin >> userAge; // Extract integer
cout << "Please enter your salary: ";
cin >> userSalary; // Extract floating-point number
// Display input results
cout << "\n=== Your Input Information ===" << endl;
cout << "Name: " << userName << endl;
cout << "Age: " << userAge << endl;
cout << "Salary: $" << userSalary << endl;
// Smart type conversion demonstration
cout << "\n=== Smart Type Conversion Demonstration ===" << endl;
int number;
cout << "Please enter a number: ";
cin >> number;
// cout automatically converts number to string for output
cout << "The number you entered is: " << number << endl;
cout << "The square of the number is: " << number * number << endl;
cout << "Half of the number is: " << number / 2.0 << endl;
return 0;
}
Using C Library Functions
#include <iostream>
#include <cmath> // C math library
#include <cstring> // C string library
#include <cstdlib> // C standard library
#include <ctime> // C time library
using namespace std;
int main() {
// Using C math library functions
cout << "=== C Math Library Function Demonstration ===" << endl;
double x = 64.0;
double y = 2.5;
cout << "sqrt(" << x << ") = " << sqrt(x) << endl; // Square root
cout << "pow(" << x << ", 0.5) = " << pow(x, 0.5) << endl; // Power operation
cout << "sin(" << y << ") = " << sin(y) << endl; // Sine
cout << "log(" << x << ") = " << log(x) << endl; // Natural logarithm
cout << "ceil(" << y << ") = " << ceil(y) << endl; // Ceiling
cout << "floor(" << y << ") = " << floor(y) << endl; // Floor
// Using C string library functions
cout << "\n=== C String Library Function Demonstration ===" << endl;
char str1[20] = "Hello";
char str2[20] = "World";
char str3[40];
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
strcpy(str3, str1); // Copy string
cout << "After copying str3: " << str3 << endl;
strcat(str3, " "); // Concatenate string
strcat(str3, str2);
cout << "After concatenating str3: " << str3 << endl;
cout << "Length of str3: " << strlen(str3) << endl; // String length
// Using C standard library functions
cout << "\n=== C Standard Library Function Demonstration ===" << endl;
int a = -10;
cout << "abs(" << a << ") = " << abs(a) << endl; // Absolute value
// Using C time library functions
cout << "\n=== C Time Library Function Demonstration ===" << endl;
time_t now = time(0); // Get current time
char* dt = ctime(&now); // Convert to string
cout << "Current time: " << dt;
// Random number generation
srand(time(0)); // Set random seed
cout << "Random number: " << rand() % 100 << endl; // Random number between 0-99
return 0;
}
Complete Comprehensive Example
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
// Class definition
class Calculator {
private:
double lastResult;
public:
Calculator() : lastResult(0) {}
// Various mathematical operations
double add(double a, double b) {
lastResult = a + b;
return lastResult;
}
double subtract(double a, double b) {
lastResult = a - b;
return lastResult;
}
double multiply(double a, double b) {
lastResult = a * b;
return lastResult;
}
double divide(double a, double b) {
if (b != 0) {
lastResult = a / b;
return lastResult;
} else {
cout << "Error: Divisor cannot be zero!" << endl;
return 0;
}
}
double power(double base, double exponent) {
lastResult = pow(base, exponent); // Using C library function
return lastResult;
}
double getLastResult() {
return lastResult;
}
};
// Function prototypes
void displayMenu();
int getChoice();
int main() {
Calculator calc;
int choice;
double num1, num2, result;
cout << "=== Simple Calculator Program ===" << endl;
do {
displayMenu();
choice = getChoice();
if (choice >= 1 && choice <= 5) {
cout << "Please enter the first number: ";
cin >> num1;
if (choice != 5) { // Power operation only needs one number
cout << "Please enter the second number: ";
cin >> num2;
}
switch (choice) {
case 1:
result = calc.add(num1, num2);
cout << num1 << " + " << num2 << " = " << result << endl;
break;
case 2:
result = calc.subtract(num1, num2);
cout << num1 << " - " << num2 << " = " << result << endl;
break;
case 3:
result = calc.multiply(num1, num2);
cout << num1 << " * " << num2 << " = " << result << endl;
break;
case 4:
result = calc.divide(num1, num2);
if (num2 != 0) {
cout << num1 << " / " << num2 << " = " << result << endl;
}
break;
case 5:
cout << "Please enter exponent: ";
cin >> num2;
result = calc.power(num1, num2);
cout << num1 << " ^ " << num2 << " = " << result << endl;
break;
}
cout << "Last result: " << calc.getLastResult() << endl;
}
cout << endl;
} while (choice != 6);
cout << "Thank you for using the calculator program!" << endl;
return 0;
}
void displayMenu() {
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division" << endl;
cout << "5. Power" << endl;
cout << "6. Exit" << endl;
}
int getChoice() {
int choice;
cout << "Please select an operation (1-6): ";
cin >> choice;
return choice;
}
Summary of Key Concepts
-
Program Structure: A C++ program consists of functions, starting execution from the main() function.
-
Function Composition: Function header (return type, function name, parameters) + Function body (collection of statements).
-
Six Types of Statements:
- Declaration statements: defining variables.
- Assignment statements: assigning values to variables.
- Message statements: communication between objects.
- Function calls: executing functions.
- Function prototypes: function declarations.
- Return statements: returning values.
Classes and Objects:
- Class: data type specification (data representation + operations).
- Object: concrete instance of a class.
Input and Output:
- cout: output object, using << insertion operator.
- cin: input object, using >> extraction operator.
- Smart type conversion.
C Library Functions: Using rich C language library functions by including corresponding header files.
Understanding these basic concepts is fundamental to mastering C++ programming, laying a solid foundation for further learning of more advanced features.