C++ Fundamentals I: Syntax, Variables, Input, Output and Data Types

3
0

C++ Fundamentals 1

C++ is a general-purpose programming language. A general-purpose language can be used across many kinds of problems and domains. This is different from a single-purpose technology such as HTML, which is mainly used to structure web pages, or SQL, which is mainly used to query databases. C++ can be used for data structures and algorithms, competitive programming, system-level programming, application development, and many other areas.

For a beginner, the purpose of learning C++ is not to memorize every feature of the language. The purpose is to gain enough command over the language to express solutions clearly and run them on a machine. In problem solving, the important journey begins with understanding the problem, identifying inputs, constraints, assumptions, and expected output, then designing and testing a solution. Once the logic is ready, a programming language gives that logic an executable form.

Why C++ Is Useful for DSA

C++ is widely used for data structures, algorithms, and competitive programming because it gives a useful combination of speed, explicitness, and control.

  • General-purpose nature: C++ can solve a wide range of problems instead of being limited to one domain.

  • Explicit types: When a variable is declared, its type is visible. This makes it easier to understand what kind of value is being stored.

  • Efficient execution: C++ is a compiled language and is known for fast performance.

  • Low-level control: When needed, C++ allows programmers to work close to memory, allocation, and system-level details.

  • High-level abstractions: C++ also provides ready-made tools and abstractions so that common operations do not need to be written from scratch every time.

  • Large standard library: Many common facilities are already implemented. For example, instead of manually multiplying 2 nine times to compute 2 to the power 9, C++ provides functions such as pow.

The standard library makes programming easier, but it does not replace problem-solving skill. A fast language cannot fix an incorrect algorithm. The language is the tool; the logic is still the programmer’s responsibility.

What to Learn First

A beginner should not try to master the entire C++ language before starting data structures and algorithms. That approach creates unnecessary pressure and delays actual problem solving. The first goal is to learn the essentials.

  • Store values such as numbers, characters, strings, and decimal values.

  • Take input from the user or from an input file.

  • Print output on the screen.

  • Calculate expressions using arithmetic operations.

  • Choose between paths using conditional statements.

  • Repeat work using loops.

  • Organize repeated logic clearly using functions.

Topics such as functions, arrays, strings, recursion, pointers, classes, and STL containers will be covered in later modules.

From Algorithm to Execution

An algorithm is a language-independent solution. It explains what needs to be done without depending on C++, Java, Python, or any other programming language.

Consider a simple problem: read two numbers and print their sum.

Algorithm

Read two numbers a and b
Set sum = a + b
Display sum

This is clear even without knowing C++. The programming language does not invent a new solution; it translates the same logic into legal syntax that the computer can compile and run.

C++ Translation

#include <iostream>
int main(){
int a, b;
std::cin >> a >> b;
sum = a + b;
std::cout << sum;
return 0;
}

The role of C++ here is to provide valid syntax for each action. Reading input, assigning a value, and displaying output all map directly to the algorithmic steps.

After code is written, it is compiled. Compilation checks whether the code follows the rules of C++. For example, most C++ statements end with a semicolon. If rules are broken, a compilation error occurs. If compilation succeeds, the program can be executed and its output can be seen.

The First C++ Program

The most basic first program prints Hello World on the screen.

#include <iostream>
int main() {
std::cout << "Hello World";
return 0;
}

#include <iostream>

C++ provides facilities through headers. The iostream header provides input and output facilities such as cin and cout. Without including the right header, the program may not know about these facilities.

For convenience, many competitive programmers use: #include <bits/stdc++.h>

This includes almost all commonly used standard headers at once. It is convenient, but it can be heavier because the compiler has more to process. For beginners and competitive programming, it is commonly seen, but understanding specific headers such as iostream, cmath, string, and iomanip is still useful.

int main()

main is the entry point of a C++ program. Normal execution begins from this function. The int before main means the function returns an integer status to the environment.

Curly Braces

The curly braces define the body of main. The statements inside these braces are the statements that belong to the function and are executed as part of it.

int main() {
// statements inside this block belong to main
}

std::cout

cout is the standard output stream. It is used to print output on the screen.

std::cout << "Hello World";

The std:: part tells C++ that cout belongs to the standard library namespace. To avoid writing std:: repeatedly, many programs write: using namespace std;

Then the code can be written as:

#include <iostream>
using namespace std;
int main() {
cout << "Hello World";
return 0;
}

return 0;

return 0; conventionally reports that the program completed successfully. In modern C++, reaching the end of main also implies successful completion, but writing return 0; makes the intention clear.

The program executes from top to bottom. If return 0; appears before a print statement, the program stops before reaching that print statement.

#include <iostream>
int main() {
return 0;
std::cout << "Hello World"; // this will not execute
}

From Source File to Running Program

A file such as main.cpp contains C++ source code. The .cpp extension indicates that the file is intended to contain C++ code.

The journey from source code to execution has several stages.

  • Preprocessing: Directives such as #include are handled. The required header declarations are made available to the source file.

  • Compilation: The compiler checks C++ syntax and language rules. If valid, the source code is translated into object code.

  • Linking: The linker combines compiled pieces and required library components into a runnable executable.

  • Execution: The operating system loads the executable into memory, gives it CPU time, and the program runs.

Failure Categories

Errors can happen at different stages. Knowing the category helps in debugging.

Compile-Time Error

A compile-time error occurs when the code violates C++ syntax or language rules. A missing semicolon is a common example.

#include <iostream>
int main() {
std::cout << "Hello World" // Missing Semi-colon
return 0;
}

The compiler may report that it expected a semicolon before return. The actual mistake is usually on the previous line.

Link-Time Error

A link-time error occurs when compiled pieces cannot be combined into a complete executable. For example, a function may be declared but not defined. This is less common for absolute beginners but becomes important when programs are split across multiple files or when using libraries.

Runtime Error

A runtime error occurs after the program successfully compiles and starts running, but something invalid happens during execution.

int a = 12 / 0;

Division by zero is not a valid operation. The syntax may look correct, but the program fails while running.

Logical Error

A logical error occurs when the program runs but produces the wrong result because the logic is incorrect. For example, marking a person younger than 18 as eligible to vote is a logical mistake. The program may compile and run, but the answer is wrong.

Comments

Comments are notes for humans. They are ignored during execution.

// This is a single-line comment
/*
This is a multi-line comment.
It can span more than one line.
*/

Comments should explain the intent behind a piece of code, especially the reasoning behind a decision, rather than simply describing what the code already makes obvious. A useful comment provides additional context that helps readers understand why an operation is necessary and makes the code easier to maintain.

// Weak comment: Merely repeats what the code does.
// Prints the age.
cout << age;
// Strong comment: Explains the reasoning behind the operation.
// Add the grace marks before checking the final eligibility.
score = score + 5;

Statements and Blocks

A statement is one executable instruction. In C++, a semicolon usually terminates a statement. The semicolon behaves like a full stop. It tells C++ that the statement is complete.

Missing Semicolon Trap

If a semicolon is missing, the compiler may report the error on the next line.

#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int age = 18
cout << age;
}
/*
Error Shown:
sol.cpp: In function ‘int main()’:
sol.cpp:7:5: error: expected ‘,’ or ‘;’ before ‘cout’
7 | cout << age;
| ^~~~
*/

The compiler may point near cout, but the real issue is that the previous statement was not properly terminated.

Blocks

A block is a group of zero or more statements inside curly braces.

{
int age = 18;
cout << age;
}

Variables declared inside a block usually belong only to that block. This is called block scope.

{
int age = 18;
cout << age; // valid
}
cout << age; // invalid: age is not accessible here

If a variable is declared outside main or outside a smaller block, it can have a wider scope. Such global declarations are accessible from more places, but scope should be used carefully in larger programs.

Output in C++

A program may calculate values internally, but nothing becomes visible unless output is produced. cout is used to display program state.

int age = 19;
age = age + 5;

This changes the value internally, but no output appears. To see the result:

int age = 19;
age = age + 5;
cout << age;

Printing Text and Variables

Text inside double quotes is printed exactly as written, while text without quotes is treated as a variable name, and its stored value is printed. Multiple values can be printed in a single statement by chaining the insertion operator (<<), allowing text and variable values to appear together in the output.

// Prints: age
cout << "age";
int age = 18;
// Prints: 18
cout << age;
// Prints: Age = 18
cout << "Age = " << age;

New Lines

If multiple outputs are printed without a new line, they appear on the same line.

cout << "Hello";
cout << "World";
// Output: HelloWorld

To move to the next line, use \n or endl.

cout << "Hello\n";
cout << "World\n";
cout << "Hello" << endl;
cout << "World" << endl;
/* Output:
Hello
World
Hello
World
*/

Both end the current line, but endl also requests a stream flush. Flushing means pushing buffered output onward immediately. For most ordinary competitive programming output, \n is preferred because unnecessary flushing can add overhead.

Escape Sequences

An escape sequence begins with a backslash and represents a character that may be difficult or special to type directly inside a string literal.

  • \n creates a new line.

  • \t creates a horizontal tab.

  • \" prints a double quote inside a string.

  • \\ prints a backslash.

cout << "Hello\nWorld";
cout << "Hello\tWorld";
cout << "He said, \"Hello\"";
cout << "C:\\Users\\Name";

Fixed Precision

Floating-point values often need controlled formatting. To print a fixed number of digits after the decimal point, use fixed with setprecision. The setprecision manipulator comes from the iomanip header.

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double price = 12.876;
cout << fixed << setprecision(1) << price;
return 0;
}

This prints 12.9 as the value is rounded using normal rounding rules. Since the digit after 8 is 7, the result becomes 12.9.

If fixed is not used, setprecision generally controls significant digits, not the exact number of digits after the decimal point.

Input in C++

Hard-coded values work only for one fixed case.

#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout << a + b;
return 0;
}

If the problem asks to read two numbers and print their sum, the program should accept input instead.

#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int sum = a + b;
cout << sum;
return 0;
}

cin is the standard input stream. The extraction operator >> reads a formatted value and stores it in the variable on its right.

cin >> a;
cin >> b;
// This can also be written in one line:
cin >> a >> b;

Input values can be separated by spaces or line breaks.

Input separated by space:
10 20
Input separated by line break:
10
20

Both can be read correctly by cin >> a >> b.

Prompts in Local Programs and Online Judges

In a local terminal program, prompts can make input easier to understand.

cout << "Enter value of first number: ";
cin >> a;
cout << "Enter value of second number: ";
cin >> b;

However, online judges usually compare the program output exactly with the expected output. Extra prompts such as Enter value of first number: can make the answer wrong even if the logic is correct. In online judge submissions, read input silently and print only the required answer.

Input Tokenization and Invalid Input

When variables are declared without initialization, they do not contain meaningful values.

int a, b;
cout << a << " " << b;

This may print garbage values because a and b have not been assigned valid values.

When cin reads into an integer variable, it expects an integer token. If the input is valid, extraction succeeds.

int a, b;
cin >> a >> b;

For input: 7 4, a becomes 7 and b becomes 4.

If the program expects an integer but receives unsuitable text, the extraction fails and the stream enters a failed state.

int a;
cin >> a;
// Let Input be "Raj"

The program cannot extract an integer from that token. In interactive software, this situation should usually be detected and handled. A basic check can be written as:

int a;
if (cin >> a) {
cout << "Valid input";
} else {
cout << "Invalid input";
}

Conditional statements are studied in detail later, but the idea here is simple: if input extraction succeeds, the input is valid for the expected type; otherwise, it is invalid.

Variables

A variable is a named object that stores a value. Example: int score = 10;

  • int is the type.

  • score is the variable name.

  • 10 is the initial value.

  • The semicolon ends the declaration statement.

A type tells the compiler how the value should be represented and which operations make sense for that value.

Declaration, Initialization, and Assignment

int score; // declaration
score = 10; // assignment
int marks = 80; // declaration with initialization
marks = 90; // later assignment

A variable’s value can be changed later unless it is declared as constant.

Updating a Variable

int score = 10;
score = score + 5;

The expression on the right side is evaluated first. The program reads the old value 10, computes 10 + 5, and stores 15 back into score.

Fundamental Data Types

int

int stores ordinary whole numbers. Example: int age = 18;

An int is commonly 4 bytes. One byte is 8 bits, so 4 bytes means 32 bits. A typical signed 32-bit integer range is approximately: -2147483648 to 2147483647

If a number goes beyond the range of int, use a larger type such as long long.

long long

long long is used for larger whole numbers. It is commonly 8 bytes, or 64 bits. Example: long long population = 9000000000;

char

char stores a single character. Character literals use single quotes. For example: char grade = 'A';

string

string stores text. String literals use double quotes. To use string, include the string header or use a combined header such as bits/stdc++.h.

#include <string>
string name = "Aman";

float and double

float and double store decimal values. double is commonly preferred for more precision. For example:

  • float temperature = 7.8;

  • double price = 8.9;

bool

bool stores either true or false. For example:

  • bool isEligible = true;

  • bool isEmpty = false;

Overflow

If an integer is already storing the largest value it can store, adding more to it causes overflow.

int a = 2147483647;
a = a + 5;

The result cannot fit into a normal 32-bit int, so the program’s behavior becomes incorrect for the intended calculation. Choose a suitable data type according to the range of values required.

Literals and Naming Rules

A literal writes a value directly in source code.

42 // integer literal
3.14 // floating-point literal
'A' // character literal
"Hello" // string literal
true // boolean literal

Identifier Rules

Variable names are identifiers. They may use letters, digits, and underscores, but they cannot begin with a digit and cannot be a reserved keyword.

int studentCount; // valid
int age_1; // valid
int 2marks; // invalid: begins with a digit
int class; // invalid: class is a reserved keyword

Use Meaningful Names

Names should reveal purpose. In small examples, names such as a and b are common, but in larger code, descriptive names are better.

int studentCount;
double totalPrice;
bool isEligible;
int digitSum;

Good names reduce the need for unnecessary comments and make code easier for other programmers to read.

Integer Division and Type Conversion Preview

When both operands of division are integers, C++ performs integer division.

int x = 5 / 2;
cout << x;
// Output: 2

The decimal part is removed.

Even if the result is stored in a double, integer division still happens first if both operands are integers.

double x = 5 / 3;
cout << x;
// Output: 1.0

This stores 1 as a double value. To get a decimal result, at least one operand must be floating-point.

double x = 5.0 / 3;
cout << x;
// Output: 1.66667

Assigning a decimal value to an integer also removes the decimal part.

int x = 3.9;
cout << x;
// Output: 3

The value stored in x is 3, not 4.

Constants

A constant is a value that cannot be changed after initialization. The keyword const is used to declare a constant value. Trying to assign a new value to a constant causes a compilation error.

const double price = 6.896;
price = 8.5; // invalid

The compiler catches this before runtime because the code violates the rule that a constant cannot be modified.

Practice Problem: Student Average

Problem: Read a student’s name and marks in three subjects, then display the average with two digits after the decimal point. Since complete string input is taught later, assume the name contains no spaces.

  • Example Input: Aman 80 75 91

  • Expected Output: 82.00

Algorithm

Read name
Read marks m1, m2, m3
average = (m1 + m2 + m3) / 3
Display average with two digits after the decimal point

The important point is that the division should produce a decimal value. Since m1, m2, and m3 are integers, dividing by 3 would perform integer division. Dividing by 3.0 ensures floating-point division.

C++ Solution

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string name;
int m1, m2, m3;
cin >> name;
cin >> m1 >> m2 >> m3;
double average = (m1 + m2 + m3) / 3.0;
cout << fixed << setprecision(2) << average;
return 0;
}

For the input Aman 80 75 91, the sum is 246. The average is 246 / 3.0, which is 82.0. With fixed and setprecision(2), it is printed as 82.00.

C++

Read Similar Blogs

Comments0