Basic Structure & Syntax
C++ Basic Structure and Syntax
Basic Structure:
A C++ program consists of one or more functions, and at least one of them must be named main
. The main
function is the entry point of the program, and execution starts from there.
// Single-line comments start with //
/*
Multi-line comments can be written like this.
*/
#include <iostream> // Include necessary libraries
// Function declaration
int main() {
// Statements inside the main function
return 0; // Indicates successful program execution
}
Basic Syntax:
1. Comments:
// This is a single-line comment
/*
This is a
multi-line comment
*/
2. Header Files:
#include <iostream> // Include the iostream library for input/output
3. Namespace:
using namespace std; // Use the standard namespace to simplify code
4. Main Function:
int main() {
// Statements go here
return 0; // Indicates successful program execution
}
5. Data Types:
int // Integer
float // Floating-point number
double // Double-precision floating-point number
char // Character
bool // Boolean (true or false)
6. Variables:
int age = 25; // Declare and initialize an integer variable
float pi = 3.14; // Declare and initialize a float variable
char grade = 'A'; // Declare and initialize a character variable
7. Input/Output:
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}
8. Conditional Statements:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
9. Loops:
for (int i = 0; i < 5; ++i) {
// Code to repeat in a loop
}
while (condition) {
// Code to repeat while the condition is true
}
do {
// Code to repeat at least once and then as long as the condition is true
} while (condition);
10. Functions:
// Function declaration
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 4); // Function call
std::cout << "Result: " << result << std::endl;
return 0;
}
11. Arrays:
int numbers[5] = {1, 2, 3, 4, 5}; // Declare and initialize an array
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
These are some of the fundamental building blocks of C++. As you progress, you'll encounter more advanced concepts like pointers, classes, templates, and the Standard Template Library (STL). Remember to practice regularly and build on your understanding by working on small projects.