0% found this document useful (0 votes)
16 views

Chapter 1

Uploaded by

tommyassefa95
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Chapter 1

Uploaded by

tommyassefa95
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter 1: Overview of Programming Using C++

What is C++
 C++ is a general purpose, case-sensitive, free-form programming language that supports
object-oriented, procedural and generic programming.
 C++ is a middle-level language, as it encapsulates both high and low level language
features.
Object-Oriented Programming (OOPs)
C++ supports the object-oriented programming, the four major pillar of object oriented
programming used in C++ are:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
C++ Standard Libraries
Standard C++ programming is divided into three important parts:
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:
o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc
C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily change the
C++ program code.
File: main.cpp
1. #include <iostream>

PREPARED BY MEDHANYE KAHSU 1

Source: Tutorials point


2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }
C++ Features
C++ is object oriented programming language. It provides a lot of features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
11. Object Oriented
12. Compiler base
C++ Basic Input / Output
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main

Header File Function and Description

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.

memory, this is called as input operation.

PREPARED BY MEDHANYE KAHSU 2

Source: Tutorials point


<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision
and setw.

<fstream> It is used to declare services for user-controlled file processing.

I/O Library Header Files


Let us see the common header files used in C++ programming are:

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator
(<<) to display the output on a console
Let's see the simple example of standard output stream (cout):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
6. }
Output:
Value of ary is: Welcome to C++ tutorial
Standard input stream (cin)
The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>)
to read the input from a console.
Let's see the simple example of standard input stream (cin):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";

PREPARED BY MEDHANYE KAHSU 3

Source: Tutorials point


6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }
Output:
Enter your age: 22
Your age is: 22
Standard end line (endl)
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
Let's see the simple example of standard end line (endl):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl;
7. }
Output:
C++ Tutorial Javatpoint
End of line

1.1. What is a Program?


A program is a set of instructions written in a programming language that a computer can execute
to perform specific tasks or solve problems. In C++, programs are compiled into machine code,
which the computer's hardware can execute directly. Programs manipulate data, perform
computations, make decisions, and manage resources to achieve desired outcomes.
1.2. The Building Blocks of Programs
In C++, programs are constructed from several fundamental components:
 Data: Information that the program processes, such as numbers, characters, and more
complex structures.

PREPARED BY MEDHANYE KAHSU 4

Source: Tutorials point


 Logic: The sequence of operations and decision-making processes that determine how
data is manipulated.
 Control Flow: The order in which instructions are executed, managed by control
statements.
 Functions: Reusable blocks of code that perform specific tasks, enhancing modularity
and readability.
1.3. Basic Elements of Programming
1.3.1. Identifiers, Variables, Literals, Constants, Keywords, Comments, Data Types,
Expressions and Operators, Statements
 Identifiers: Names given to various program elements like variables, functions, and
classes. They must follow specific naming rules in C++.
int age; // 'age' is an identifier
 Variables: A variable is a name of memory location with a name and a data type that
hold values which can change during program execution. It is used to store data. Its value
can be changed and it can be reused many times. It is a way to represent memory location
through symbol so that it can be easily identified.

int count = 10; // 'count' is a variable of type int


Let's see the syntax to declare a variable:
1. type variable_list;
The example of declaring variable is given below:
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1. int x=5,b=10; //declaring 2 variable of integer type
2. float f=30.8;
3. char c='A';

PREPARED BY MEDHANYE KAHSU 5

Source: Tutorials point


Rules for defining variables
 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only. It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float etc.
 Valid variable names:
1. int a;
2. int _ab;
3. int a30;
Invalid variable names:
1. int 4;
2. int x y;
3. int double;

 Literals: Fixed values directly used in the code.


int number = 100; // 100 is an integer literal
double pi = 3.14159; // 3.14159 is a floating-point literal
char letter = 'A'; // 'A' is a character literal
std::string greeting = "Hello, World!"; // "Hello, World!" is a string literal
 Constants: Variables whose value cannot be altered once initialized, declared using the
const keyword.
const double PI = 3.14159;
 Keywords: Reserved words in C++ that have special meanings and cannot be used as
identifiers. A list of 32 Keywords in C++ Language which are also available in C
language are given below.

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

PREPARED BY MEDHANYE KAHSU 6

Source: Tutorials point


struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given
below.

asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t

Examples include int, return, if, else, for, while, etc.


 Comments: Non-executable text used to describe and explain code, enhancing
readability.
// This is a single-line comment

/*
This is a multi-line comment
spanning multiple lines
*/
 Data Types: Define the type of data a variable can hold. Common C++ data types
include: There are 4 types of data types in C++ language.

Types Data Types

PREPARED BY MEDHANYE KAHSU 7

Source: Tutorials point


Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports both
signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

PREPARED BY MEDHANYE KAHSU 8

Source: Tutorials point


signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte

Example int age = 25;


double salary = 55000.50;
char grade = 'A';
bool isEmployed = true;

 Expressions: Combinations of variables, literals, and operators that evaluate to a value.


int sum = a + b; // 'a + b' is an expression
 Operators: Symbols that perform operations on variables and values.
o Arithmetic Operators: +, -, *, /, %
o Relational Operators: ==, !=, >, <, >=, <=

PREPARED BY MEDHANYE KAHSU 9

Source: Tutorials point


o Logical Operators: &&, ||, !
o Assignment Operators: =, +=, -=, *=, /=
o Increment/Decrement Operators: ++, --
int a = 5;
int b = 10;
int c = a + b; // c is 15
bool isEqual = (a == b); // isEqual is false
a += 2; // a is now 7
C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator

PREPARED BY MEDHANYE KAHSU 10

Source: Tutorials point


Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left.
Let's understand the precedence by the example given below:
1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before +
(additive operator).
The precedence and associativity of C++ operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Right to left

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == !=/td> Right to left

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Right to left

PREPARED BY MEDHANYE KAHSU 11

Source: Tutorials point


Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= Right to left


^= |=

Comma , Left to right

 Statements: Instructions that perform actions. Each statement ends with a semicolon (;)
in C++.
int x = 10; // Declaration and initialization statement
x = x + 5; // Assignment statement
std::cout << x; // Function call statement
1.4. Control Statements
Control statements manage the flow of execution in a C++ program, allowing for decision-
making, looping, and altering the execution path.
1.4.1. Decision/Conditional Statements
These statements enable the program to execute certain blocks of code based on specified
conditions.
C++ if-else
In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.

PREPARED BY MEDHANYE KAHSU 12

Source: Tutorials point


1. if(condition){
2. //code to be executed
3. }
C++ If Example
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num = 10;
5. if (num % 2 == 0)
6. {
7. cout<<"It is even number";
8. }
9. return 0;
10. }

Output:/p>
It is even number
C++ IF-else Statement
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

PREPARED BY MEDHANYE KAHSU 13

Source: Tutorials point


C++ If-else Example
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num = 11;
5. if (num % 2 == 0)
6. {
7. cout<<"It is even number";
8. }
9. else
10. {
11. cout<<"It is odd number";
12. }
13. return 0;
14. }

Output:
It is odd number
C++ If-else Example: with input from user
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a Number: ";
6. cin>>num;
7. if (num % 2 == 0)
8. {
9. cout<<"It is even number"<<endl;
10. }
11. else
12. {

PREPARED BY MEDHANYE KAHSU 14

Source: Tutorials point


13. cout<<"It is odd number"<<endl;
14. }
15. return 0;
16. }
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number

C++ IF-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

PREPARED BY MEDHANYE KAHSU 15

Source: Tutorials point


C++ If else-if Example
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. if (num <0 || num >100)
8. {
9. cout<<"wrong number";
10. }
11. else if(num >= 0 && num < 50){

PREPARED BY MEDHANYE KAHSU 16

Source: Tutorials point


12. cout<<"Fail";
13. }
14. else if (num >= 50 && num < 60)
15. {
16. cout<<"D Grade";
17. }
18. else if (num >= 60 && num < 70)
19. {
20. cout<<"C Grade";
21. }
22. else if (num >= 70 && num < 80)
23. {
24. cout<<"B Grade";
25. }
26. else if (num >= 80 && num < 90)
27. {
28. cout<<"A Grade";
29. }
30. else if (num >= 90 && num <= 100)
31. {
32. cout<<"A+ Grade";
33. }
34. }
Output:
Enter a number to check grade:66
C Grade
Output:
Enter a number to check grade:-2
wrong number

PREPARED BY MEDHANYE KAHSU 17

Source: Tutorials point


 switch: switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C++.

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
13. }

PREPARED BY MEDHANYE KAHSU 18

Source: Tutorials point


C++ Switch Example
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 10: cout<<"It is 10"; break;
10. case 20: cout<<"It is 20"; break;
11. case 30: cout<<"It is 30"; break;
12. default: cout<<"Not 10, 20 or 30"; break;
13. }
14. }

Output:

Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30

1.4.2. Loops
Loops enable the repeated execution of a block of code as long as a specified condition remains
true.

For loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.

1. for(initialization; condition; incr/decr){


2. //code to be executed
3. }

Flowchart:

PREPARED BY MEDHANYE KAHSU 19

Source: Tutorials point


C++ For Loop Example
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested For Loop


In C++, we can use for loop inside another for loop, it is known as nested for loop. The
inner loop is executed fully when outer loop is executed one time. So if outer loop and inner
loop are executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total
16 times.

C++ Nested For Loop Example


Let's see a simple example of nested for loop in C++.

1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){

PREPARED BY MEDHANYE KAHSU 20

Source: Tutorials point


7. cout<<i<<" "<<j<<"\n";
8. }
9. }
10. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinite For Loop


If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple
example of infinite for loop in C++.

1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for (; ;)
6. {
7. cout<<"Infinitive For Loop";
8. }
9. }

Output:

Infinitive For Loop


Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c

 for: Ideal for scenarios where the number of iterations is known beforehand.
// Print numbers from 1 to 5
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";

PREPARED BY MEDHANYE KAHSU 21

Source: Tutorials point


}
// Output: 1 2 3 4 5
 while: Continues to execute a block of code as long as the condition is true. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.

1. while(condition){
2. //code to be executed
3. }

Flowchart:

C++ While Loop Example


Let's see a simple example of while loop to print table of 1.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }

PREPARED BY MEDHANYE KAHSU 22

Source: Tutorials point


10. }

Output:

1 4 7
2 5 8
3 6 9
10

C++ Nested While Loop Example


In C++, we can use while loop inside another while loop, it is known as nested while loop.
The nested while loop is executed fully when outer loop is executed once.

Let's see a simple example of nested while loop in C++ programming language.

1. #include <iostream>
2. using namespace std;
3. int main () {
4. int i=1;
5. while(i<=3)
6. {
7. int j = 1;
8. while (j <= 3)
9. {
10. cout<<i<<" "<<j<<"\n";
11. j++;
12. }
13. i++;
14. }
15. }

Output:

1 1 2 1 3 1
1 2 2 2 3 2
1 3 2 3 3 3

C++ Infinitive While Loop Example:


We can also create infinite while loop by passing true as the test condition.

1. #include <iostream>
2. using namespace std;
3. int main () {

PREPARED BY MEDHANYE KAHSU 23

Source: Tutorials point


4. while(true)
5. {
6. cout<<"Infinitive While Loop";
7. }
8. }

Output:

Infinitive While Loop


Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c
 do..while: Similar to while, but guarantees that the block of code is executed at least once. If
the number of iteration is not fixed and you must have to execute the loop at least once,
it is recommended to use do-while loop.

The C++ do-while loop is executed at least once because condition is checked after loop
body.

1. do{
2. //code to be executed
3. }while(condition);

Flowchart:

PREPARED BY MEDHANYE KAHSU 24

Source: Tutorials point


C++ do-while Loop Example
Let's see a simple example of C++ do-while loop to print the table of 1.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9. }

Output:

1 5 9
2 6 10
3 7
4 8
C++ Nested do-while Loop
In C++, if you use do-while loop inside another do-while loop, it is known as nested do-
while loop. The nested do-while loop is executed fully for each outer do-while loop.

Let's see a simple example of nested do-while loop in C++.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. int j = 1;
7. do{
8. cout<<i<<"\n";
9. j++;
10. } while (j <= 3) ;
11. i++;
12. } while (i <= 3) ;
13. }

Output:

PREPARED BY MEDHANYE KAHSU 25

Source: Tutorials point


1 1 2 1 3 1
1 2 2 2 3 2
1 3 2 3
3 3

C++ Infinitive do-while Loop


In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

1. do{
2. //code to be executed
3. }while(true);

C++ Infinitive do-while Loop Example


1. #include <iostream>
2. using namespace std;
3. int main() {
4. do{
5. cout<<"Infinitive do-while Loop";
6. } while(true);
7. }

Output:

Infinitive do-while Loop


Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c

1.4.3. Flow Control Statements


These statements alter the normal flow of execution within loops and functions.
 break: Exits the nearest enclosing loop or switch statement immediately.
for (int i = 1; i <= 10; ++i) {
if (i == 6) {
break; // Exit the loop when i is 6
}
std::cout << i << " ";
}
// Output: 1 2 3 4 5
 continue: Skips the current iteration of a loop and proceeds to the next iteration.

PREPARED BY MEDHANYE KAHSU 26

Source: Tutorials point


for (int i = 1; i <= 5; ++i) {
if (i == 3) {
continue; // Skip printing when i is 3
}
std::cout << i << " ";
}
// Output: 1 2 4 5
 goto: Transfers control to a labeled statement. Note: The use of goto is generally
discouraged as it can lead to code that is difficult to read and maintain.
int main() {
int num = 1;
start:
std::cout << num << " ";
num++;
if (num <= 5) {
goto start; // Jumps back to the 'start' label
}
return 0;
}
// Output: 1 2 3 4 5
 return: Exits a function and optionally returns a value to the caller.
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
int main() {
int sum = add(5, 3);
std::cout << "Sum: " << sum; // Output: Sum: 8
return 0;
}

PREPARED BY MEDHANYE KAHSU 27

Source: Tutorials point

You might also like