Professional Documents
Culture Documents
C++ Programming: For Beginners
C++ Programming: For Beginners
C++ Programming
For Beginners
By: Natnael Abebe
IC++
Contents
1. Getting Started With C++ ................................................................................................................................................ 2
1.1. Introduction............................................................................................................................................................... 2
1.1.1. What is C++? .................................................................................................................................................... 2
1.1.2. Why Learn C++? .............................................................................................................................................. 2
1.1.3. Key Concepts in C++ ...................................................................................................................................... 2
1.1.4. How to Write and Run a Simple C++ Program ...................................................................................... 2
1.1.5. Setting Up Your Environment ..................................................................................................................... 3
1.1.6. Compiling and Running Your Program .................................................................................................... 3
1.2. Syntax in C++ Programming.................................................................................................................................. 3
1.2.1. Basic Structure of a C++ Program ............................................................................................................. 3
1.3. C++ Variables .............................................................................................................................................................4
1.3.1. Declaring (Creating) Variables ............................................................................................................................. 5
1.3.2. Constants .................................................................................................................................................................. 5
1.4. Data Types ................................................................................................................................................................ 6
1.4.1. Type Modifiers .......................................................................................................................................................... 7
1.5. C++ User Input ........................................................................................................................................................ 10
1.6. Operators ................................................................................................................................................................. 10
1.6.1. Arithmetic Operators ........................................................................................................................................... 10
Exercise 1 ..................................................................................................................................................................................12
1.7. C++ Assignment Operators ................................................................................................................................. 14
1.8. C++ Comparison Operators ................................................................................................................................ 14
1.9. C++ Logical Operators .......................................................................................................................................... 14
1.10. C++ Strings .......................................................................................................................................................... 15
1.10.1. String Concatenation............................................................................................................................................17
1.10.2. String Functions................................................................................................................................................... 18
Question 1: Palindrome Check ..................................................................................................................................... 19
1.10.3. Numbers and Strings.......................................................................................................................................... 19
1.11. C++ Math ............................................................................................................................................................ 20
1.11.1. Max and min .......................................................................................................................................................... 20
1.11.2. C++ <cmath> Header ........................................................................................................................................... 20
1
1. GETTING STARTED WITH C++
1.1. Introduction
1.1.1. What is C++?
C++ (pronounced "C plus plus") is a powerful and versatile programming language that was developed as
an extension of the C language. It was created by Bjarne Stroustrup in 1983 and has since become one of
the most widely used programming languages in the world.
Syntax: The set of rules that define how a C++ program is written and interpreted.
Variables: Containers for storing data values.
Data Types: Define the type of data a variable can hold (e.g., int for integers, char for characters).
Functions: Blocks of code that perform specific tasks and can be reused throughout the program.
Control Structures: Direct the flow of the program (e.g., if statements, loops).
Arrays: Collections of variables that are accessed with an index number.
Pointers: Variables that store memory addresses, providing a way to manipulate data in memory.
2
#include <iostream>: This line tells the compiler to include the standard input-output
stream library, which is necessary for input and output operations.
int main(): This is the main function where the execution of the program starts. Every C++
program must have a main function.
std::cout << "Hello, World!";: This line prints the text "Hello, World!" to the screen.
std::cout is used for output.
return 0;: This line ends the main function and returns 0 to indicate that the program ran
successfully.
1. A Text Editor or an Integrated Development Environment (IDE): Popular options include Visual
Studio Code, Code::Blocks, and Dev-C++.
2. A C++ Compiler: The compiler translates the C++ code into machine code that the computer can
execute. Common compilers include GCC (GNU Compiler Collection) and Clang.
1. Preprocessor Directives
2. Main Function
3. Statements and Expressions
Preprocessor directives are lines included in the code that begin with the # symbol. They are processed
before the actual compilation of the code begins.
#include <iostream>: This directive tells the compiler to include the standard input-
output stream library, which allows the program to use cout for output.
Using Namespace: The using namespace std; directive tells the compiler to use the standard
namespace. This means you can use names for objects and variables from the standard library
without the std:: prefix.
using namespace std;: This line allows you to use cout instead of std::cout.
2. Main Function
The main function is where the execution of any C++ program begins. It has the following syntax:
int main(): Declares the main function which returns an integer value.
{}: Curly braces enclose the body of the function where statements and code are written.
return 0;: Indicates that the program ended successfully. The 0 is a status code returned to the
operating system.
3. Statements and Expressions
Statements in C++ are instructions that the compiler can execute. Each statement ends with a semicolon (;).
cout << "Hello, World!";: This statement uses the output stream object cout to print the text "Hello,
World!" to the screen. The << operator is used to send the text to the output stream.
return 0;: This statement ends the main function and returns 0 to the operating system.
Comments are non-executable parts of the code that are used to explain what the code does. They are
ignored by the compiler. In C++, comments can be single-line or multi-line.
Single-line comment: Starts with // and continues to the end of the line.
Multi-line comment: Starts with /* and ends with */
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
4
1.3.1. Declaring (Creating) Variables
To create a variable, specify the type and assign it a value:
Where type is one of C++ types (such as int), and variableName is the name of the variable
identifier (such as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
#include <iostream>
using namespace std;
int main() {
// Integer data type
int age = 18;
int year = 2024;
// Floating-point data type
float height = 5.9f;
double weight = 70.5;
// Character data type
char grade = 'A';
// Boolean data type
bool isStudent = true;
// String data type
string name = "Alice";
// Output the values of the variables
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Year: " << year << endl;
cout << "Height: " << height << " feet" << endl;
cout << "Weight: " << weight << " kg" << endl;
cout << "Grade: " << grade << endl;
cout << "Is Student: " << (isStudent ? "Yes" :
"No") << endl;
return 0;
}
1.3.2. Constants
When you do not want others (or yourself) to change existing variable values, use the const keyword
(this will declare the variable as "constant", which means unchangeable and read-only):
5
1.4. Data Types
C++ provides a rich set of built-in data types to work with different kinds of data. Understanding these data
types is essential for managing and manipulating data effectively in your programs.
1. Integer Types
2. Floating-Point Types
3. Character Types
6
4. Boolean Type
5. String Type
signed: Default modifier for most integer types, can hold negative and positive values.
unsigned: Can hold only positive values.
short: Reduces the size of an integer.
long: Increases the size of an integer.
7
#include <iostream>
#include <string>
int main() {
// Integer types
int age = 18;
short year = 2024;
long population = 7800000000L;
long long bigNumber = 123456789012345LL;
unsigned int positiveNumber = 42;
// Floating-point types
float height = 5.9f;
double weight = 70.5;
long double preciseValue = 3.14159265358979323846L;
// Character types
char grade = 'A';
wchar_t wideChar = L'Ω';
// Boolean type
bool isStudent = true;
bool isTall = false;
// String type
string name = "Alice";
return 0;
8
QUATIONS
#include <iostream>
int main() {
cout << "Hello, World!"
int age = 18;
float height = 5.9;
char grade = 'A';
bool isStudent = true;
string name = "Alice";
cout << "Name: " << name << endl
cout << "Age: " << age << endl;
cout << "Height: " << height << endl;
cout << "Grade: " << grade << endl;
cout << "Is Student: " << (isStudent ? "Yes" : "No") <<
endl;
return 0;
}
Declare and initialize variables of different data types to represent the following information:
A short integer for the number of days in a week.
An unsigned integer for the number of students in a class.
A double for the value of pi (3.14159).
A character for the first letter of your name.
A boolean to indicate if you are a C++ programmer.
Given the following variables, match them to their appropriate data types and indicate the typical memory
size they occupy:
cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
In the following example, the user can input a number, which is stored in the variable x. Then we print the
value of x:
int x;
cout << "Type a number: " ; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
1.6. Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
10
++ Increment Increases the value of a ++x
variable by 1
-- Decrement Decreases the value of a --x
variable by 1
#include <iostream>
int main() {
int a, b;
cout << "Enter two integers to add: ";
cin >> a >> b;
int sum = a + b;
return 0;
}
#include <iostream>
int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
int sum = a + b + c;
float average = sum / 3.0;
return 0;
}
11
Exercise 1
Q1. Write a C++ program to calculate Compound interest. Compound interest is the interest on a loan or
deposit that is calculated based on both the initial principal and the accumulated interest from previous
periods. Unlike simple interest, which is calculated only on the principal amount, compound interest is
calculated on the principal plus any interest that has been added to it.
Principal (P): This is the initial amount of money that you have invested or borrowed.
Rate (R): This is the annual interest rate, expressed as a percentage.
Time (T): This is the time the money is invested or borrowed for, usually measured in years.
Number of times interest is compounded per year (n): This is how many times the interest is
applied to the principal in a year. Common compounding frequencies include annually, semi-
annually, quarterly, monthly, daily, etc.
A=P(1+R/100n)nt
pow((1 + rate / 100), time);
#include <iostream>
#include <cmath>
int main() {
float principal, rate, time, compoundInterest;
return 0;
}
12
Q2. Write a C++ program Program to Convert Celsius to Fahrenheit in C++. The formula is 𝐹�=(𝐶�×9/5)+32
to convert the temperature to Fahrenheit.
#include <iostream>
int main() {
float celsius, fahrenheit;
return 0;
}
#include <iostream>
int main() {
float length, width, area, perimeter;
return 0;
}
13
1.7. C++ Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
int x = 10;
The return value of a comparison is either 1 or 0, which means true (1) or false (0). In the following
example, we use the greater than operator (>) to find out if 5 is greater than 3:
int x= 5;
int y= 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
Logical operators are used to determine the logic between variables or values:
14
true
Question 1
Write a C++ program that evaluates a complex logical expression. The program should read four boolean
values from the user and check if at least one of the first two values is true and both of the last two values
are true. Use logical operators and assignment operators to evaluate the expression and store the result.
#include <iostream>
int main() {
bool a, b, c, d, result;
return 0;
}
Creating Strings
You can create a string in C++ using the string class:
#include <iostream>
#include <string>
int main() {
string greeting = "Hello, World!";
cout << greeting << endl;
15
return 0;
}
Explanation:
#include <iostream>
#include <string>
int main() {
string name;
cout << "Enter your name: ";
cin >> name; // This will read only the first word entered
by the user
cout << "Hello, " << name << "!" << endl;
return 0;
}
Note: Using cin with strings will only capture the first word entered. To capture a full line of text, use
getline:
#include <iostream>
#include <string>
int main() {
string fullName;
cout << "Enter your full name: ";
getline(cin, fullName); // This reads an entire line of
text
cout << "Hello, " << fullName << "!" << endl;
return 0;
}
16
1.10.1. String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
#include <iostream>
#include <string>
int main() {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; //
Concatenating strings
cout << "Full Name: " << fullName << endl;
return 0;
}
Append
A string in C++ is actually an object, which contain functions that can perform certain operations on
strings. For example, you can also concatenate strings with the append() function:
#include <iostream>
#include <string>
int main() {
// Initialize first and last name strings
string firstName = "John ";
string lastName = "Doe";
return 0;
} 17
1.10.2. String Functions
Length of a String: Use the length() or size() method.
#include <iostream>
#include <string>
int main() {
string str = "Hello";
cout << "Length of string: " << str.length() << endl; //
or str.size()
return 0;
}
#include <iostream>
#include <string>
int main() {
string str = "Hello";
cout << "First character: " << str[0] << endl; // Using []
cout << "Second character: " << str.at(1) << endl; //
Using at()
return 0;
}
#include <iostream>
#include <string>
int main() {
string str = "Hello, World!";
18 5); // Extracting "World"
string substr = str.substr(7,
cout << "Substring: " << substr << endl;
return 0;
}
String Comparison: Use the compare() method to compare two strings.
#include <iostream>
#include <string>
int main() {
string str1 = "Hello";
string str2 = "World";
if (str1.compare(str2) == 0) {
cout << "Strings are equal" << endl;
} else {
cout << "Strings are not equal" << endl;
}
return 0;
}
Note: C++ uses the + operator for both addition and concatenation. Numbers are added.
Strings are concatenated.
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
string x = "10";
string y = "20";
string z = x + y; // z will be191020 (a string)
1.11. C++ Math
C++ has many functions that allow you to perform mathematical tasks on numbers.
Q1 Write a C++ program that calculates the square root of a number provided by the user.
#include <iostream>
#include <cmath>
int main() {
double number, result;
cout << "Enter a number: ";
cin >> number;
if (number < 0) {
cout << "Cannot calculate the square root of a negative
number." << endl;
} else {
result = sqrt(number);
cout << "The square root of " << number << " is " << result
<< endl;
}
return 0;
}
20
Q2 Write a C++ program that takes a base and an exponent from the user and calculates the power using
the pow() function.
#include <iostream>
#include <cmath>
int main() {
double base, exponent, result;
cout << "Enter the base: ";
cin >> base;
cout << "Enter the exponent: ";
cin >> exponent;
return 0;
}
Q3 Write a C++ program that calculates the hypotenuse of a right-angled triangle given the lengths of the
other two sides.
#include <iostream>
#include <cmath>
int main() {
double side1, side2, hypotenuse;
cout << "Enter the length of the first side: ";
cin >> side1;
cout << "Enter the length of the second side: ";
cin >> side2;
return 0;
}
21
Q4 Write a C++ program that calculates the area of a circle given its radius.
#include <iostream>
#include <cmath>
int main() {
double radius, area;
cout << "Enter the radius of the circle: ";
cin >> radius;
return 0;
}
#include <iostream>
#include <cmath>
int main() {
double degrees, radians;
cout << "Enter the angle in degrees: ";
cin >> degrees;
return 0;
}
22