1
ITCP- Mid
Table of Contents
1. Introduction to Programming and C++
- 1.1 What is C++?
- 1.2 History of C++
- 1.3 Importance and Applications
- 1.4 Setting Up the Development Environment
- 1.5 Rules for a C++ Program and Syntax
2. Basic Syntax
- 2.1 Structure of a C++ Program
- 2.2 Data Types and Variables
- 2.3 Input and Output (I/O) Operations
- 2.4 Constants
- 2.5 Comments
3. Operators
- 3.1 Arithmetic Operators
- 3.2 Relational Operators
- 3.3 Logical Operators
- 3.4 Assignment Operators
- 3.5 Increment and Decrement Operators
4. Control Structures
- 4.1 Conditional Statements
- 4.2 Switch Statement
- 4.3 Loops
- 4.4 Break and Continue Statements
5. Functions
- 5.1 Function Definition and Declaration
- 5.2 Calling Functions
- 5.3 Function Overloading
- 5.4 Default Arguments
- 5.5 Scope of Variables
6. Arrays
- 6.1 Introduction to Arrays
- 6.2 Initializing Arrays
2
Chapter 1: Introduction to Programming and C++
Programming languages are formal languages comprised of a set of instructions that can
be used to produce various kinds of output, including software applications, algorithms,
and data manipulation. They allow developers to communicate with computers and
instruct them on what to do.
High-level vs. Low-level
High-level languages (like Python, Java) are easier for humans to read and write, while
low-level languages (like Assembly) are closer to machine code.
Compiler
A compiler is a special program that translates code written in a high-level programming
language into machine code (or intermediate code) that a computer's processor can
execute.
Key Functions:
- Translation: Converts the entire source code into machine code before execution.
- Error Checking: Identifies syntax and semantic errors during the compilation process.
- Optimization: Can optimize the code for better performance.
Example:
- C Compiler: Converts C code into executable machine code.
Interpreter
An interpreter is a program that directly executes instructions written in a high-level
programming language, translating them into machine code line-by-line or statement-
by-statement during runtime.
Key Functions:
- Execution: Reads and executes the source code on-the-fly.
- Error Handling: Catches errors as they occur during execution, allowing for interactive
debugging.
Example:
- Python Interpreter: Executes Python code directly without compiling it into machine
code first.
3
Summary
- Programming Languages: Tools for writing software.
- Compiler: Translates high-level code into machine code in one go, resulting in a
standalone executable.
- Interpreter: Executes high-level code directly, translating it as needed during
execution.
Note that both compilers and interpreters play crucial roles in programming, and the
choice between them often depends on the specific needs of a project or the language
being used.
1.1 What is C++?
C++ is a programming language that allows you to create software. It is an extension of
the C language and includes features that help you organize your code better. With C++,
you can build anything from simple programs to complex systems. This flexibility makes
it a favorite among developers.
1.2 History of C++
C++ was developed in the early 1980s by Bjarne Stroustrup. He wanted to add features
to C that would support better data organization. C++ introduced object-oriented
programming (OOP), which allows programmers to create classes and objects, making
code more modular and reusable.
1.3 Importance and Applications
C++ is widely used in various fields:
- Game Development: Games like “Counter-Strike” and “World of Warcraft” are made
with C++ because it allows for high performance and complex graphics.
- System Software: C++ is used to build operating systems, including parts of Windows
and Linux.
- Embedded Systems: Devices like microwaves and cars often run software written in C+
+ because it can interact directly with hardware.
- Financial Applications: Many banks and trading platforms rely on C++ for its speed and
efficiency in handling large amounts of data.
4
1.4 Setting Up the Development Environment
To write and run C++ programs, you need to set up your environment:
1. Choose an IDE: An Integrated Development Environment, like Visual Studio,
Code::Blocks, or Eclipse, helps you write code with tools like syntax highlighting and
debugging features.
2. Install a Compiler: A compiler, such as GCC or MSVC, translates your C++ code into
machine code that your computer can execute. Most IDEs come with a compiler built-in.
3. Write Your First Program: Start with a simple program to ensure everything is
working.
Example 1: Hello World Program
#include <iostream> // Include the library for input and output
using namespace std; // Use the standard namespace
int main() { // Main function where execution starts
cout << "Hello, World!" << endl; // Print a greeting message
return 0; // Indicate that the program ended successfully
}
1.5 Rules for a C++ Program and Syntax
When writing C++ programs, you should follow some basic rules:
1. Every Program Needs a Main Function: The `main()` function is the entry point of a C+
+ program. Without it, the program won't run.
2. Use of Semicolons: Every statement must end with a semicolon (`;`). This helps the
compiler understand where one statement ends and the next begins.
3. Case Sensitivity: C++ is case-sensitive. For example, `Variable` and `variable` are
different identifiers.
4. Comments: Use comments to explain your code. Comments start with `//` for single
lines or use `/* */` for multiple lines. They are ignored by the compiler but help others
(or you) understand your code later.
5. Proper Indentation: While not required, proper indentation helps make your code
readable. Use spaces or tabs consistently.
5
6. Include Necessary Libraries: Use `#include` to include libraries at the top of your
program. For example, `#include <iostream>` includes the necessary tools for input and
output operations.
Chapter 2: Basic Syntax
2.1 Structure of a C++ Program
Understanding the structure of a C++ program is essential. Here's what you typically see:
- Preprocessor Directives: Lines starting with `#` tell the compiler to include libraries or
define constants. For instance, `#include <iostream>` includes functions for input and
output.
- Namespace Declaration: The line `using namespace std;` allows you to use standard
functions like `cout` and `cin` without typing `std::` each time.
- Main Function: The line `int main()` defines the main function where the program
execution begins.
- Statements: Inside the main function, you write statements that the program will
execute.
Example 1: Basic Structure
#include <iostream> // Include the library for input/output
using namespace std; // Use the standard namespace
int main() { // Main function starts here
cout << "This is a simple C++ program." << endl; // Print a message
return 0; // End of the program
}
2.2 Data Types and Variables
Data types define the type of data a variable can hold. Here's a breakdown:
- int: Represents integer values (e.g., -3, 0, 42).
- float: Represents floating-point numbers (e.g., 3.14, -0.01).
- char: Represents single characters (e.g., 'A', 'b').
6
- bool: Represents boolean values (true or false).
Declaring variables allows you to store and manipulate data.
Example 2: Variable Declaration
#include <iostream>
using namespace std;
int main() {
int number = 5; // Declare an integer variable
float decimal = 5.5; // Declare a float variable
char letter = 'A'; // Declare a char variable
bool isTrue = true; // Declare a boolean variable
// Output the values of the variables
cout << "Number: " << number << ", Decimal: " << decimal
<< ", Letter: " << letter << ", Is True: " << isTrue << endl;
return 0;
}
2.3 Input and Output (I/O) Operations
C++ provides ways to take input from the user and display output:
- cout: This is used to print output to the console.
- cin: This is used to read input from the user.
Using these two makes your program interactive.
Example 3: I/O Operations
#include <iostream>
using namespace std;
int main() {
int num; // Declare an integer variable
cout << "Enter a number: "; // Prompt the user
cin >> num; // Read the user's input
7
cout << "You entered: " << num << endl; // Display the entered number
return 0;
}
2.4 Constants
Constants are values that do not change throughout the program. Declaring a constant
makes your code safer and clearer. You can define a constant using the `const` keyword.
Example 4: Using Constants
#include <iostream>
using namespace std;
int main() {
const float PI = 3.14; // Define a constant for Pi
cout << "Value of PI: " << PI << endl; // Output the constant
return 0;
}
2.5 Comments
Comments are notes in your code that the compiler ignores. They help you and others
understand your code. Always use comments to explain complex parts of your code or
to clarify your intentions.
Example 5: Comments
// This is a single-line comment
/*
This is a multi-line comment.
It helps to explain the code in detail.
*/
#include <iostream>
using namespace std;
int main() {
cout << "Comments are useful!" << endl; // Print a message
return 0;
}
8
9
Chapter 3: Operators
3.1 Arithmetic Operators
Arithmetic operators perform mathematical operations. Here are the main ones:
- Addition (`+`): Adds two numbers.
- Subtraction (`-`): Subtracts one number from another.
- Multiplication (`*`): Multiplies two numbers.
- Division (`/`): Divides one number by another.
- Modulus (`%`): Gives the remainder of a division operation.
Understanding these operators helps you perform calculations in your programs.
Example 1: Arithmetic Operations
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20; // Declare two integers
cout << "Sum: " << (a + b) << endl; // Outputs the sum
cout << "Difference: " << (a - b) << endl; // Outputs the difference
cout << "Product: " << (a * b) << endl; // Outputs the product
cout << "Quotient: " << (b / a) << endl; // Outputs the quotient
cout << "Remainder: " << (b % a) << endl; // Outputs the remainder
return 0;
}
3.2 Relational Operators
Relational operators compare two values and return true or false:
- Equal to (`==`): Checks if two values are equal.
- Not equal to (`!=`): Checks if two values are different.
- Greater than (`>`): Checks if one value is greater than another.
- Less than (`<`): Checks if one value is less than another.
- Greater than or equal to (`>=`): Checks if one value is greater than or equal to another.
10
- Less than or equal to (`<=`): Checks if one value is less than or equal to another.
Using relational operators helps in making decisions based on comparisons.
Example 2: Relational Operations
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20; // Declare two integers
cout << "Is a equal to b? " << (a == b) << endl; // Outputs 0 (false)
cout << "Is a not equal to b? " << (a != b) << endl; // Outputs 1 (true)
cout << "Is a greater than b? " << (a > b) << endl; // Outputs 0 (false)
cout << "Is a less than b? " << (a < b) << endl; // Outputs 1 (true)
return 0;
}
3.3 Logical Operators
Logical operators are used to combine or invert boolean values:
- AND (`&&`): Returns true if both conditions are true.
- OR (`||`): Returns true if at least one condition is true.
- NOT (`!`): Inverts the value (true becomes false and vice versa).
These operators are essential for making complex conditions in decision-making
statements.
Example 3: Logical Operations
#include <iostream>
using namespace std;
int main() {
bool a = true, b = false; // Declare two boolean variables
cout << "a AND b: " << (a && b) << endl; // Outputs 0 (false)
cout << "a OR b: " << (a || b) << endl; // Outputs 1 (true)
cout << "NOT a: " << (!a) << endl; // Outputs 0 (false)
return 0;
11
3.4 Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment
operator is `=`. There are also combined operators like `+=`, `-=`, `*=`, and `/=`.
Example 4: Assignment Operations
#include <iostream>
using namespace std;
int main() {
int a = 10; // Initialize a variable
a += 5; // Same as a = a + 5
cout << "Value of a: " << a << endl; // Outputs 15
a *= 2; // Same as a = a * 2
cout << "Value of a: " << a << endl; // Outputs 30
return 0;
}
3.5 Increment and Decrement Operators
These operators increase or decrease the value of a variable by 1:
- Increment (`++`): Increases a variable’s value by 1.
- Decrement (`--`): Decreases a variable’s value by 1.
You can use them in two ways:
- Prefix (e.g., `++a`): Increases the value before it’s used.
- Postfix (e.g., `a++`): Increases the value after it’s used.
Understanding these helps in loops and iterative processes.
Example 5: Increment and Decrement
#include <iostream>
using namespace std;
int main() {
int a = 5; // Initialize a variable
cout << "Value of a: " << a << endl; // Outputs 5
cout << "Incrementing a: " << ++a << endl; // Outputs 6 (prefix increment)
cout << "Now a: " << a << endl; // Outputs 6
cout << "Decrementing a: " << --a << endl; // Outputs 5 (prefix decrement)
12
cout << "Now a: " << a << endl; // Outputs 5
return 0; }
13
Chapter 4: Control Structures
4.1 Conditional Statements
Conditional statements allow your program to make decisions. The `if` statement checks
a condition and executes code only if that condition is true. You can also use `else` to
execute code when the condition is false.
Example 1: If-Else Statement
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age; // Take user input
if (age >= 18) {
cout << "You are an adult." << endl; // Executes if true
} else {
cout << "You are a minor." << endl; // Executes if false
}
return 0;
}
4.2 Switch Statement
The `switch` statement is another way to make decisions. It checks a variable against a
list of values. It’s often easier than using multiple `if` statements when you have many
conditions.
Example 2: Switch Statement
#include <iostream>
using namespace std;
int main() {
int day;
14
cout << "Enter a day (1-7): ";
cin >> day; // Take user input
switch (day) {
case 1:
cout << "Monday" << endl;
break; // Exit the switch after a match
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 << "Invalid day!" << endl; // Executes if no case matches
break;
}
return 0;
}
4.3 Loops
Loops allow you to repeat a block of code multiple times. The most common loops in C+
+ are `for`, `while`, and `do-while` loops.
Example 3: For Loop
#include <iostream>
15
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) { // Loop from 1 to 5
cout << "Iteration: " << i << endl; // Print the current iteration
}
return 0;
}
Example 4: While Loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) { // Loop while i is less than or equal to 5
cout << "Iteration: " << i << endl; // Print the current iteration
i++; // Increment i
}
return 0;
}
Example 5: Do-While Loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << "Iteration: " << i << endl; // Print the current iteration
i++; // Increment i
} while (i <= 5); // Check the condition after the first iteration
return 0;
}
16
4.4 Break and Continue Statements
These statements control the flow of loops. `break` exits a loop immediately, while
`continue` skips the current iteration and moves to the next one.
Example 1: Break Statement
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i equals 3
}
cout << "Iteration: " << i << endl;
}
return 0;
}
Example 2: Continue Statement
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the current iteration when i equals 3
}
cout << "Iteration: " << i << endl;
}
return 0;
}
17
Chapter 5: Functions
5.1 Function Definition and Declaration
Functions are blocks of code that perform a specific task. They help organize code and
make it reusable. You declare a function before using it.
Example 1: Function Definition
#include <iostream>
using namespace std;
void greet() { // Function definition
cout << "Hello!" << endl; // Code that runs when the function is called
}
int main() {
greet(); // Calling the function
return 0;
}
5.2 Calling Functions
You can call functions in your program to execute the code inside them.
Example 2: Calling a Function
#include <iostream>
using namespace std;
void displayMessage() {
cout << "This is a message from a function." << endl;
}
int main() {
displayMessage(); // Call the function to display the message
return 0;
}
18
5.3 Function Overloading
Function overloading allows you to create multiple functions with the same name but
different parameters. The compiler determines which function to call based on the
arguments you pass.
Example 3: Function Overloading
#include <iostream>
using namespace std;
int add(int a, int b) { // Function to add two integers
return a + b;
}
float add(float a, float b) { // Overloaded function for floats
return a + b;
}
int main() {
cout << "Integer addition: " << add(3, 4) << endl; // Calls the first function
cout << "Float addition: " << add(3.5f, 4.5f) << endl; // Calls the second function
return 0;
}
5.4 Default Arguments
Default arguments allow you to provide default values for function parameters. If a user
does not pass a value, the default will be used.
Example 4: Default Arguments
#include <iostream>
using namespace std;
void printInfo(string name, int age = 18) { // Default age is 18
cout << "Name: " << name << ", Age: " << age << endl;
}
19
int main() {
printInfo("Alice"); // Uses default age
printInfo("Bob", 25); // Overrides default age
return 0;
}
5.5 Scope of Variables
The scope of a variable defines where it can be accessed in your program. Variables
declared inside a function can only be used within that function.
Example 5: Variable Scope
#include <iostream>
using namespace std;
void myFunction() {
int x = 10; // x is local to myFunction
cout << "Inside function: " << x << endl;
}
int main() {
myFunction();
// cout << x; // This would cause an error because x is not accessible here
return 0;
}
20
Chapter 6: Arrays
6.1 Introduction to Arrays
Arrays are collections of variables of the same type. They allow you to store multiple
values in a single variable.
Example 1: Declaring an Array
#include <iostream>
using namespace std;
int main() {
int numbers[5]; // Declare an array of 5 integers
return 0;
}
6.2 Initializing Arrays
You can initialize an array when you declare it. This means you give it specific values
right from the start.
Example 2: Array Initialization
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5}; // Initialize an array with values
return 0;
}