Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

DILLA UNIVERSITY STEM CENTER

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.

1.1.2. Why Learn C++?


 Foundation for Other Languages: Learning C++ provides a solid foundation for understanding other
programming languages, as many modern languages are influenced by C++.
 Performance: C++ is known for its performance and efficiency, making it ideal for developing games,
operating systems, and other performance-critical applications.
 Versatility: C++ can be used for a wide range of applications, from system software to game
development and web applications.
 Object-Oriented Programming (OOP): C++ supports OOP, which helps in organizing code and
making it more modular, reusable, and easier to manage.

1.1.3. Key Concepts in C++


Before diving into C++, it's helpful to understand some basic concepts:

 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.

1.1.4. How to Write and Run a Simple C++ Program


Here is a simple example of a C++ program that prints "Hello, World!" to the screen:

#include <iostream> // This is a library that allows


for input and output operations
int main() { // This is the main function, where the
execution of the program begins
std::cout << "Hello, World!"; // This line prints
"Hello, World!" to the screen
return 0; // This indicates that the program ended
successfully
}

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.1.5. Setting Up Your Environment


To start programming in C++, you need:

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.1.6. Compiling and Running Your Program


1. Write Your Code: Write your C++ code in a text editor or IDE and save it with a .cpp extension (e.g.,
hello.cpp).
2. Compile the Code: Open your terminal or command prompt and navigate to the directory where
your file is saved. Compile the code using a compiler command, such as g++ hello.cpp -o hello.
3. Run the Program: After compiling, run the executable file that was generated by the compiler. For
example, ./ hello on Unix-based systems or hello.exe on Windows.

1.2. Syntax in C++ Programming


Syntax in programming refers to the set of rules that define the structure and arrangement of statements in
a programming language. Just like grammar rules in English, syntax rules in C++ must be followed to write
correct and understandable code.

1.2.1. Basic Structure of a C++ Program


A basic C++ program consists of several parts:

1. Preprocessor Directives
2. Main Function
3. Statements and Expressions

Let's break down each part with an example:

#include <iostream> // Preprocessor directive

using namespace std; // Using the standard namespace

int main() { // Main function


cout << "Hello, World!"; // Statement
return 0; // Statement
}
3
1. Preprocessor Directives

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 */

1.3. C++ Variables


Variables are containers for storing data values.

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:

Syntax type variableName = 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):

const int myNum = 15; // myNum will always be 15


myNum = 10; // error: assignment of read-only variable 'myNum'

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

Integers are used to store whole numbers without a fractional component.

 int: Standard integer type.


 short: Short integer type, usually 2 bytes.
 long: Long integer type, usually 4 or 8 bytes.
 long long: Long long integer type, usually 8 bytes.
 unsigned: Modifier to store only non-negative integers.

int age = 18;


short year = 2024;
long population = 7800000000L;
long long bigNumber = 123456789012345LL;
unsigned int positiveNumber = 42;

2. Floating-Point Types

Floating-point numbers are used to represent numbers with a fractional component.

 float: Single precision floating-point type.


 double: Double precision floating-point type.
 long double: Extended precision floating-point type.

float height = 5.9f;


double weight = 70.5;
long double preciseValue = 3.14159265358979323846L;

3. Character Types

Characters are used to store individual characters.

 char: Standard character type, usually 1 byte.


 wchar_t: Wide character type, used for larger character sets.

char grade = 'A';


wchar_t wideChar = L'Ω';

6
4. Boolean Type

Booleans are used to represent true or false values.

 bool: Boolean type.

bool isStudent = true;


bool isTall = false;

5. String Type

Strings are used to store sequences of characters.

 string: Standard string type from the C++ Standard Library.

string name = "Alice";

1.4.1. Type Modifiers


C++ allows you to modify the properties of the fundamental data types using type modifiers.

 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.

unsigned short smallNumber = 65535;


long long largeNumber = 9223372036854775807LL;

7
#include <iostream>
#include <string>

using namespace std;

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";

// 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 << "Wide Character: " << wideChar << endl;
cout << "Is Student: " << (isStudent ? "Yes" : "No") <<
endl;
cout << "Is Tall: " << (isTall ? "Yes" : "No") << endl;
cout << "Population: " << population << endl;
cout << "Big Number: " << bigNumber << endl;
cout << "Positive Number: " << positiveNumber << endl;
cout << "Precise Value: " << preciseValue << endl;

return 0;

8
QUATIONS

 What is wrong with this program

#include <iostream>

using namespace std;

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.

 Data Types and Memory Size

Given the following variables, match them to their appropriate data types and indicate the typical memory
size they occupy:

short smallNumber = 32767;


unsigned long largePositiveNumber = 4294967295;
float temperature = 98.6f;
double distance = 12345.6789;
char initial = 'M';
bool isRaining = false;
9
1.5. C++ User Input
You have already learned that cout is used to output (print) values. Now we will use cin to get user
input.

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:

int x = 100 + 50;

int sum1 = 100 + 50; // 150 (100 + 50)


int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

1.6.1. Arithmetic Operators

Operator Name Description Example

+ Addition Adds together two x+y


values
- Subtraction Subtracts one value x-y
from another
* Multiplication Multiplies two values x*y
/ Division Divides one value by x/y
another
% Modulus Returns the division x%y
remainder

10
++ Increment Increases the value of a ++x
variable by 1
-- Decrement Decreases the value of a --x
variable by 1

Ex. Adding Two Numbers

#include <iostream>

using namespace std;

int main() {
int a, b;
cout << "Enter two integers to add: ";
cin >> a >> b;

int sum = a + b;

cout << "Sum: " << sum << endl;

return 0;
}

Ex. Finding the Sum and Average of Three Numbers

#include <iostream>

using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

int sum = a + b + c;
float average = sum / 3.0;

cout << "Sum: " << sum << endl;


cout << "Average: " << average << endl;

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.

Here's a detailed explanation of how compound interest works:

 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.

The formula for calculating compound interest is:

A=P(1+R/100n)nt
pow((1 + rate / 100), time);

#include <iostream>
#include <cmath>

using namespace std;

int main() {
float principal, rate, time, compoundInterest;

cout << "Enter principal amount: ";


cin >> principal;
cout << "Enter annual interest rate (in %): ";
cin >> rate;
cout << "Enter time (in years): ";
cin >> time;

compoundInterest = principal * pow((1 + rate / 100), time);

cout << "Compound Interest: " << compoundInterest << endl;

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>

using namespace std;

int main() {
float celsius, fahrenheit;

cout << "Enter temperature in Celsius: ";


cin >> celsius;

fahrenheit = (celsius * 9/5) + 32;

cout << "Temperature in Fahrenheit: " << fahrenheit <<


endl;

return 0;
}

Q3 Write a C++ program to Calculating Area and Perimeter of a Rectangle.

#include <iostream>

using namespace std;

int main() {
float length, width, area, perimeter;

cout << "Enter length and width of the rectangle: ";


cin >> length >> width;

area = length * width;


perimeter = 2 * (length + width);

cout << "Area: " << area << endl;


cout << "Perimeter: " << perimeter << endl;

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;

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

1.8. C++ Comparison Operators


Comparison operators are used to compare two values (or variables). This is important in programming,
because it helps us to find answers and make decisions.

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

1.9. C++ Logical Operators


As with comparison operators, you can also test for true (1) or false (0) values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10
| Logical or Returns true if one of the statements is true x<5| x<4
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10

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>

using namespace std;

int main() {
bool a, b, c, d, result;

cout << "Enter four boolean values (0 for false, 1 for


true): ";
cin >> a >> b >> c >> d;

// Evaluate the complex logical expression


result = (a || b) && (c && d);

cout << "The result of the expression (a || b) && (c &&


d) is: " << result << endl;

return 0;
}

1.10. C++ Strings


Strings in C++ are used to represent a sequence of characters. C++ provides a built-in string class, which is
part of the C++ Standard Library, to handle and manipulate strings.

Creating Strings
You can create a string in C++ using the string class:

#include <iostream>
#include <string>

using namespace std;

int main() {
string greeting = "Hello, World!";
cout << greeting << endl;
15
return 0;
}
Explanation:

 #include <string>: This includes the string library.


 string greeting = "Hello, World!";: This creates a string variable and initializes it with "Hello, World!".
 cout << greeting << endl;: This prints the string to the console.

Getting User Input


You can also get a string input from the user using cin:

#include <iostream>
#include <string>

using namespace std;

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>

using namespace std;

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>

using namespace std;

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>

using namespace std;

int main() {
// Initialize first and last name strings
string firstName = "John ";
string lastName = "Doe";

// Append lastName to firstName


string fullName = firstName.append(lastName);

// Output the full name


cout << "Full Name: " << fullName << endl;

return 0;
} 17
1.10.2. String Functions
 Length of a String: Use the length() or size() method.

#include <iostream>
#include <string>

using namespace std;

int main() {
string str = "Hello";
cout << "Length of string: " << str.length() << endl; //
or str.size()
return 0;
}

 Accessing Characters: Use the [] operator or the at() method.

#include <iostream>
#include <string>

using namespace std;

int main() {
string str = "Hello";
cout << "First character: " << str[0] << endl; // Using []
cout << "Second character: " << str.at(1) << endl; //
Using at()
return 0;
}

 Substring: Use the substr() method to extract a substring.

#include <iostream>
#include <string>

using namespace std;

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>

using namespace std;

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;
}

Question 1: Palindrome Check


Problem: Write a C++ program that checks if a given string is a palindrome. A palindrome is a word, phrase,
number, or other sequence of characters that reads the same forward and backward (ignoring spaces,
punctuation, and case).

Question 2: Anagram Check


Problem: Write a C++ program that checks if two given strings are anagrams of each other. Two strings are
anagrams if they contain the same characters in the same frequencies, ignoring spaces and case.

1.10.3. Numbers and Strings

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.

1.11.1. Max and min


The max(x,y) function can be used to find the highest value of x and y:

cout << max(5, 10);


cout << min(5, 10);

1.11.2. C++ <cmath> Header


Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can
be found in the <cmath> header file:
#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

Q1 Write a C++ program that calculates the square root of a number provided by the user.

#include <iostream>
#include <cmath>

using namespace std;

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>

using namespace std;

int main() {
double base, exponent, result;
cout << "Enter the base: ";
cin >> base;
cout << "Enter the exponent: ";
cin >> exponent;

result = pow(base, exponent);


cout << base << " raised to the power of " << exponent << "
is " << result << endl;

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>

using namespace std;

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;

hypotenuse = sqrt(pow(side1, 2) + pow(side2, 2));


cout << "The hypotenuse is " << hypotenuse << endl;

return 0;
}

21
Q4 Write a C++ program that calculates the area of a circle given its radius.

#include <iostream>
#include <cmath>

using namespace std;

int main() {
double radius, area;
cout << "Enter the radius of the circle: ";
cin >> radius;

area = M_PI * pow(radius, 2);


cout << "The area of the circle is " << area << endl;

return 0;
}

Q5 Write a C++ program that converts an angle from degrees to radians.

#include <iostream>
#include <cmath>

using namespace std;

int main() {
double degrees, radians;
cout << "Enter the angle in degrees: ";
cin >> degrees;

radians = degrees * (M_PI / 180.0);


cout << degrees << " degrees is " << radians << " radians."
<< endl;

return 0;
}

22

You might also like