C++ Syntax
beginnerPart of C++ Basics
Theory
C++ syntax builds on C with additional features. Every program needs a main function and uses iostream for input/output.
Program Structure and iostream
#include <iostream>
int main() {
// Program code
return 0;
}#include <iostream> brings in the standard input/output library. The program starts executing from main().
cout and cin
cout (console output) uses the insertion operator <<:
std::cout << "Hello" << std::endl;cin (console input) uses the extraction operator >>:
int age;
std::cin >> age;For strings with spaces, use std::getline:
std::string name;
std::getline(std::cin, name);Namespaces
using namespace std; allows you to omit the std:: prefix, but it's better to use specific using declarations or the std:: prefix to avoid naming conflicts.
Variables and Data Types
C++ is statically typed. Common types include:
| Type | Size | Example |
|------|------|---------|
| int | 4 bytes | int count = 10; |
| double | 8 bytes | double price = 19.99; |
| char | 1 byte | char grade = 'A'; |
| bool | 1 byte | bool flag = true; |
| std::string | variable | std::string name = "Alice"; |
Practical Examples
Exercises
Circle Calculator
Write a C++ program that asks the user for the radius of a circle, then calculates and prints the area and circumference. Use const for PI and appropriate data types.
Expected Output:
Enter radius: 5\nArea: 78.5397\nCircumference: 31.4159