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

Computer Programming - Chapter 2

The document is a comprehensive guide on C++ programming fundamentals, covering algorithms, flowcharts, and the structure of C++ programs. It explains the phases of program execution, variable declaration, data types, and operators in C++. Additionally, it includes exercises and examples to illustrate key concepts in programming.

Uploaded by

wedneshneri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Computer Programming - Chapter 2

The document is a comprehensive guide on C++ programming fundamentals, covering algorithms, flowcharts, and the structure of C++ programs. It explains the phases of program execution, variable declaration, data types, and operators in C++. Additionally, it includes exercises and examples to illustrate key concepts in programming.

Uploaded by

wedneshneri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

1

HARAMAYA UNIVERSITY
HARAMAYA INSTITUTE OF TECHNOLOGY
SCHOOL OF ELECTRICAL & COMPUTER ENGINEERING

COMPUTER PROGRAMMING
2
2. Fundamentals of C++ Programming
 Introduction
 Algorithm and Flow Chart
 Basics of C++ Programming
 Variables And Assignment
 Declaration and Initialization
 Input /Output
3
2.1 Algorithm and Flow Chart
 Algorithm is part of the blueprint or plan for the computer program.
 It is an effective procedure for solving a problem in a finite number of steps.
 There are three different ways of stating algorithms:
 Step-Form – step-by-step procedure
 Pseudocode – code like algorithm
 Flowchart – Graphical design
 Algorithms show these three features:
1. Sequence (also known as Process): means that each step or process in the
algorithm is executed in the specified order.
4
… Cont’d
2. Decision (also known as Selection):
 In algorithms the outcome of a decision is either true or false, there is no in between.
 The outcome of the decision is based on some condition that can only result in a true
or false value.
3. Repetition (also known as Iteration or Looping)
 Repetition takes two forms, the Repeat loop and the While loop.
 The repeat loop is used to iterate or repeat a process or sequence of processes
until some condition becomes true.
5
… Cont’d
• Algorithm could be designed using Basic flowcharting symbols
many techniques and tools.
• One tool of designing algorithm is
by using flowcharts.
• Flowchart is a graphical way of
expressing the steps needed to
solve a problem.
• A flow chart is a schematic
(diagrammatic description)
representation of a process.
Examples
6

1. Find the sum of five numbers using flowchart.


2. Check weather the number entered is odd or even using flowchart.
3. Write Algorithm and flowchart to find solution of quadratic equation
4. Write An algorithm to check weather a number is positive or negative

Haramaya University, HIT, SECE 1 May 2025


7
Example 1
Check weather the number entered is odd or even using flowchart
8

Haramaya University, HIT, SECE 1 May 2025


9
Example 3
10
Example 4
 An algorithm to check weather a number is positive or negative
Exercise 1.
11

1. Obtain two numbers from the keyboard, and determine and display
which (if either) is the larger of the two numbers
2. Find the average, maximum, minimum, and sum of three numbers given
by the user.
3. Take an integer from the user and display the factorial of that number.
4. Find the area of a circle where the radius is provided by the user.
5. Receive 3 numbers and display them in ascending order from smallest
to largest

Haramaya University, HIT, SECE 1 May 2025


12
2.3 Basics of C++ Programming
 Software:
 Consists of a sequence of instructions given to perform some predefined task.
 Computer program:
 A series of instructions written in some computer language and performs a particular task.
 Written by a high level programming languages
 There must be a translation process to convert high level languages to machine code.
◼ This is often done by a compiler,
 Compiler:
 A software package that translates high level languages into machine code.
 Without it we could not run our programs.
 Called Integrated development Environment (IDE)
13
… Cont’d
 An integrated development environment (IDE) is a software
package that bundles
 An editor (used to write programs),
 A compiler (that translates programs) and
 A run time component
 For example
 Microsoft Visual C++
 Dev C++
 Code Block
 NetBeans
 Visual Studio
14
… Cont’d
15
… Cont’d
• Compile, Link & Run Steps
16
Phases of C++ to be executed
 C++ programs typically go through five phases to be executed
 These are
1. Edit,

2. Preprocess,

3. Compile,

4. Link,

5. Load
17
1. Edit
• This is accomplished with an editor program.
• The programmer types C++ statements with the editor and makes corrections if
necessary.
• The programs source file is then stored on secondary storage device such as a disk with
a “.cpp” file name.
• After the program is edited, C++ is principally compiled in three phases:
1. Preprocessing,
2. Translation to object code, and
3. Linking
18
2. Preprocess
 In a C++ system, a preprocessor program executes automatically before
the compiler’s translation phase begins.
 The C++ preprocessor obeys command called preprocessor directives,
 Which indicate that certain manipulations are to be performed on the program
before compilation.
 The preprocessor is invoked by the compiler before the program is
converted to machine language.
 The C++ preprocessor goes over the program text and carries out the
instructions specified by the preprocessor directives (e.g., #include).
 The result is a modified program text which no longer contains any
directives.
19
3. Compile
 The C++ compiler translates the program code.
 The compiler translates machine independent high level source code
into machine dependent object code.
 The compiler may be a true C++ compiler which generates native
(assembly or machine) code.
 The outcome may be incomplete due to the program referring to
library routines
 Which are not defined as a part of the program.
 For example, the << operator which is actually defined in a separate
IO library.
20
4. Linking
 C++ programs typically contain references to functions and data
defined else where, such as in the standard libraries.
 The object code produced by the C++ compiler typically contains
“holes” due to these missing parts.
 A linker links the object code with the code for the missing function
to produce an executable image (with no missing pieces).
 Generally, the linker completes the object code by linking it with
the object code of any library modules that the program may
have referred to.
 The final result is an executable file (.exe)
21
5. Loading
 The loader takes the executable file from disk and transfers it to
memory.
 Additional components from shared libraries that support the
program are also loaded.
 Finally, the computer, under the control of its CPU, executes the
program.
 In practice all these steps are usually invoked by a single command
and the user will not even see the intermediate files generated.
22
Summary of C++ program phases to be executed
23
Structure of C++program
• The structure of a simple C++ program will have the following format:
Source code Output
24
… Cont’d
// my first program in C++
This is a comment line.
 They can be used by the programmer to include short explanations or observations within the source
itself.
 Comments are pieces of source code discarded from the code by the compiler.
 They do nothing other than giving information for the reader.
 Their purpose is only to allow the programmer to insert notes or descriptions embedded within
the source code.
 C++ supports two ways to insert comments:
1) // line comment
2) /* block comment */
 Line comment: discards everything from where the pair of slash signs (//) is found up to the
end of that same line.
 Block comment: discards everything between the /* characters and the next appearance of
the */ characters, with the possibility to include several lines.
25
… Cont’d
#include<iostream>
 Sentences that begin with a pound/hash sign (#) are directives for the preprocessor.
 It tells the preprocessor to include the iostream standard file.
 This specific file (iostream) includes the declarations of the basic standard input-
output library in C++
Using namespace std;
❑ All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std.
 Classes and functions of the standard libraries are located within the std namespace
 we must use the C++ using directive
 The header: • would be equivalent to the old expression
#include <iostream.h>
26
… Cont’d
void/int main ()
 This line corresponds to the beginning of the main function declaration.
 The main function is the point by where all C++ programs begin their execution.
 It does not matter whether there are other functions with other names
defined before or after it.
 The instructions contained within this function's definition will always be the
first ones to be executed in any C++ program.

cout << "Hello World!";


 This instruction does the most important thing in this program.
 cout is the standard output stream in C++ (usually the screen),
 The full sentence inserts a sequence of characters into this output stream (the screen).
 cout is declared in the iostream header file, so in order to be able to use it that file
must be included.
27
… Cont’d
 In C++ the separation between instructions is specified with an ending
semicolon (;) after each one.
 This character is used to mark the end of the statement.

 it must be included at the end of all expression statements in all C++


programs.
 We can write many statements per line or write a single statement that takes
many code lines.
 The division of code in different lines serves only to make it more legible and
schematic for the humans that may read it.
return 0;
❑ The return statement causes the main function to finish.

❑ A return code of 0 for the main function is generally interpreted as the


program worked as expected without any errors during its execution.
28
Example 2
29
Example 3 (a)
 In C++, you can print output on different lines using std:endl or the
newline character \n.
Source code Output
30
Example 3 (b)

Source code Output


31
Cont…
 in C++, \t is used as a tab character.
 It inserts a horizontal space (typically equivalent to 4 or 8 spaces
depending editor settings).
 It is commonly used for aligning output in a structured format.
Source code Output
32
Exercise 2
a) What is/are the output for the following code:
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to the wonderful world of C++!!! \n";
cout<<"Lab1 \t";
cout<<’’Exercise 1 \n”;
return 0;
}
33
… Cont’d
b) Write a program to print the following text:
Hello in my university
I am a student in the faculty
Welcome.
c) Find the errors in the following code.
#include <iostream.h>
using namespace std;
int main
{
cout >> "C++ first exam /n";
cout<<"\n END\t PROGRAM\t BYE;
}
34
2.4 Variables and assignment
 A variable is a reserved place in memory to store information in.
 Variables are used for holding data values so that they can be used in
various computations in a program.
 Variables can be found in mathematics. You must have seen statements such
as: A= 1; or a =5; or c=a+b etc.
 Variables hold values or data for a period and reference a particular area
of memory.
 Like many other programming languages, C++ uses variables.
 Each variable should have a distinct name or identifier.
 Instead of calling a variable by the letters of the alphabet, we could give
the variable useful names such as result
 As long as the name is not reserved as an exclusive C++ identifier.
35
Components of Variable
 A variable will have three components:
1. Data Type: Describes the property of the data and the size of the
reserved memory.
e.g. integer, character etc
2. Name: used to refer to the value in the variable.
❑ A unique identifier for the reserved memory location.

3. Value: a value which can be changed by assigning a new value to the


variable.
Example: int age =20;
36
Signed and Unsigned integer
 Signed integers are either negative or positive.
 Unsigned integers are always positive.
❖ If we use signed, we can use the first bit to
represent the sign where
➢ if the value of the first bit is 0 the number
is positive, and
➢ if the value is 1 the number is negative.
❑ In case of unsigned, since all the 4 bits represent
the magnitude of the number.
❑ In case of signed, we will be left with only three
bits to represent the magnitude of the number.
37
Declaring Variables
 In order to use a variable in C++, we must first declare it specifying which of the
data types we want it to be.
 The syntax to declare a new variable is:
dataType identifier;
variableType variableName;
❑ The declaration will instruct the computer to reserve a memory location with the name
and size specified during the declaration.
E.g. int myAge; //variable used to store my age
38
Identifiers
 A valid identifier or variable name is a sequence of one or more letters, digits, or
underscores characters (_).
 Spaces, punctuation marks, and symbols cannot be part of an identifier.
 Identifiers shall always begin with a letter.
 They can also begin with an underline character.
 In no case can it begin with a digit.
 C++ language is case sensitive so a capital variable identifier is different from
lowercase variable identifier.
Eg: variable Name is not identical with variable name
 Certain words are reserved by C++ for specific purposes and can not be used as
identifiers.
39
• Some examples of reserved identifiers/keywords in C++ are:
40
Data Types
 Data Types used in C++ are:
1) Character types:
 They can represent a single character, such as ‘A’ or ‘$’.
 The most basic type is char, which is a one-byte character. (ex: Char)
2) Numerical integer types:
 They can store a whole number value, such as 7 or 1024.
 They exist in a variety of sizes, and can be either signed or unsigned, depending on
whether they support negative values or not. (ex: int)
3) Floating-point types:
 They can represent real values, such as 3.14 or 0.01, with different levels of precision,
depending on which of the three floating-point types is used. (ex: float, double)
4) Boolean type:
 The Boolean type, known in C++ as bool, can only represent one of two states, true or
false. (ex: bool)
41
… Cont’d
• The list of data types used in C++:
42
Operators in C++
• Some of the operators used to manipulate C++ data are:
1. Assignation (=): The assignation operator serves to assign a value to a
variable. a = 5; //This statement assigns the integer value 5 to the variable a.
a = b;// This statement assigns to variable a the value contained in variable b.
43
Operators in C++…
2. Arithmetic operators: (+, - , * , / , and % module).
❖ Modulo is the operation that gives the remainder of a division of two values.
a = 11 % 3; // a will contain the value 2, since 2 is the remainder from dividing 11
between 3.
44
Operators in C++…
3. Compound assignation operators: (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=).
❖ When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators
45
Operators in C++…
4. Increase and decrease: increase operator (++) and decrease operator (--).
❑ The increase operator (++) is equivalent to +=1 and the decrease operator (--) is
equivalent to -=1
Ex: c++; c+=1; c=c+1; //all are equivalent in its functionality: the three of them
increase by one the value of c.
❑ This operator can be used both as a prefix and as a suffix.
❑ Prefix (++a) the value is increased before the result of the expression is evaluated
and therefore the increased value is considered in the outer expression;
❑ Suffix (a++) the value stored in a is increased after being evaluated and therefore
the value stored before the increase operation is evaluated in the outer expression.
46
Example
Source code Output
47
Operators in C++
5. Relational operators: that can be performed in C++: == Equal, != Different, >
Greater than, < Less than, >= Greater or equal to, and <= Less or equal to.
 The operator = (1 equal sign) is not the same as the operator == (2 equal signs),
 The first one (=) is an assignment operator (assigns the value at its right to the
variable at its left)
 The other one (==) is the equality operator that compares whether both expressions
in the two sides of it are equal to each other.
48
Operators in C++
6. Logic operators: ! not, && and, || or, Conditional operator ?,
➢ The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one
operand, located at its right.
➢ The only thing that it does is to inverse the value of it, producing false if its operand is true
and true if its operand is false. It returns the opposite Boolean value of evaluating its operand.

❖ The operator && corresponds with Boolean logical operation AND.


❖ The operator || corresponds with Boolean logical operation OR.
➢ This operation results true if either one of its two operands is true, thus being false only
when both operands are false themselves.
49
Operators in C++…
Conditional operator ?
Syntax: condition ? result1 : result2
❑ If condition is true the expression will return result1, if it is not it will return result2.
50
Escape Codes
 Escape codes are special characters that cannot be expressed
otherwise in the source code of a program, like newline (\n) or
tab (\t).
 All of them are preceded by an inverted slash (\).
 The backslash causes an “escape” from the normal way characters
are interpreted.
 \n newline, \r carriage return, \t tabulation, \v vertical
tabulation, \b backspace, \f page feed, \a alert (beep), \'
single quotes, \" double quotes, \ question (?), \\ inverted
slash
51
Variable Declaration and initialization

 To declare a variables of different types we write as


follows:
int a;
int b;
float firstnumber:
double w;
char a;
 We can also declare more than one variable of the same
type in a single line as follows:
int x, y, z;
52
… Cont’d
 The syntax to initialize a new variable is:
dataType identifier=value;
variableType variableName=value;
 Examples
int a=10;
int b=-20;
float firstnumber=3.809:
double w=-2.115498752568;
char a=‘w’;
 We can also initialize more than one variable of the same type
in a single line as follows:
int x=10, y=20, z=30;
53
Constant Data
 With the const prefix you can declare constants with a specific
type exactly as you would do with a variable
const int width = 100;
#define pi=3.1415;
 A sequence of two or more characters are called string.
 While a character represents a single symbol such as ‘A’ or a
‘$’ a string represents a compound type in C++.
 To use a string we need to include a new directive, # include
<string>, in addition to the directive iostream.
 We use cout to output the value of x to the screen.
54
… Cont’d
//Example 3: Variable initialization
#include <iostream>
using namespace std;
int main ()
{
int x=5; // initial value: 5
int y=2; // initial value: 2
int z;
z = x + y;
cout << z;
return 0;
}
55
Example 4
Source code Output
56
… Cont’d
// Example 5: string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string x;
x = “This is an example of a string”;
cout << x;
return 0;
}
57
… Cont’d
// Example 6: assignment operator
#include <iostream>
using namespace std;
int main ()
{
int x, y;
x = 5; // x:5, y:
y = 2; // x:5, y:2
x = y; // x:2, y:2
y = 3; // x:2, y:3
cout << “x:”;
cout << x;
cout << “y:”;
cout << y;
}
58
… Cont’d
• Use of operators
 x = 10 % 4; will give the  (7 == 8) is false
value of 2 to x  5 > 3 is true
 a += x; means a= a + x;  1 != 2 is true
 x -=10; means x = x-10;  7 >= 7 is true
 9 < = 8 is false
 y /= x; means y = y / x;
 9 = = 7 ? 5: 3 will give the result
 z *= x; means z = z * x 3 because 9 and 7 are not equal
 y++; means y = y + 1;  7 = = 6 + 1 ? 5: 3 will give the
 x--; means x = x - 1; result 5
59
… Cont’d
// Example 6: conditional operator
#include <iostream>
using namespace std;
int main ()
{
int x, y, z;
x=1;
y=5;
z = (x < y) ? 5: x;
cout << z << ‘\n’;
return 0;
}
60
Precedence of Operators
Level Precedence group Operator Description Grouping

1 Scope :: scope qualifier Left-to-right


2 Postfix (unary) ++, — Increment, decrement Left-to-right
3 Prefix (unary) ++,— prefix increment / decrement Right-to-left
4 Pointer-to-member .* ->* access pointer Left-to-right
5 Arithmetic: scaling */% multiply, divide, modulo Left-to-right
6 Arithmetic: addition +- addition, subtraction Left-to-right
7 Bitwise shift << >> shift left, shift right Left-to-right
8 Relational < > <= >= comparison operators Left-to-right
9 Equality == != equality / inequality Left-to-right
10 And & bitwise AND Left-to-right
11 Exclusive or ^ bitwise XOR Left-to-right
12 Inclusive or | bitwise OR Left-to-right
13 Conjunction && logical AND Left-to-right
61
Example
 a==b+c*d
 c * d is evaluated first because * has a higher precedence than + and = =.
 The result is then added to b because + has a higher precedence than = =
 And then == is evaluated.
 Precedence rules can be overridden by using brackets.
E.g. rewriting the above expression as:
 a = = (b + c) * d causes + to be evaluated before *.
 Operators with the same precedence level are evaluated in the order
 specified by the column on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated
followed by a = b.
62
Example
Source code Output
63
Scope of a variable
 Variables declared inside a function or block are local variables.
 Only statements that are inside that function or block of code can use them.
 Local variables are not known to functions outside their own.
 Global variables are defined outside of all the functions, usually on
top of the program.
 The global variables will hold their value throughout the lifetime of
your program.
 A global variable can be accessed by any function.
 That is, a global variable is available for use throughout the entire program.
64
Scope of a variable…
65
… Cont’d
//Example 7: Local Variables //Example 8: Global Variables
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main () int t;
{ int main ()
int x, y; {
int z;
x=10;
x =10;
y =20;
y =20;
t = x + y;
z = x + y;
cout << t;
cout << z;
return 0;
return 0;
}
}
66
2.5 Input /output
• Input and Output data streaming objects used in C++ are:

Stream Description
cin standard input
cout standard output
cerr standard error –output
clog standard logging- output
67
Cout
 cout is used with insertation operator, <<, which is used for
data insertion.
 Each cout line produces a line of words on a separate line only
if the end line \n or endl is used.
 Otherwise, the lines will be written one after the other on the
same line.
 Example:
cout << “Sentence 1”; // prints Sentence 1
cout << 100; // prints 100
cout << x; // prints the value of x
68
… Cont’d
 Text is enclosed in double quotes as shown in previous example.
 Multiple insertion operations (<<) may be chained in a single
statement.
cout << “This is” << “a” << “a valid statement”;
 What cout will not do automatically is add line breaks at the end,
unless instructed to do so.
 So if one writes the following lines of code:
cout << “This is line 1.”;
cout << “This is line 2.”;
 Then the output will be in a single line without any line breaks in
between as shown below:
This is line 1. This is line 2.
69
… Cont’d
 To insert a line break, a new line character should be
included as follows:
cout << “This is line 1.\n”;
cout << “This is line 2.\n”;
 Now the output will be:
This is line1.
This is line 2.

 Another way is to use endl. For example:


cout << “This is line 1.” << endl;
cout << “This is line 2.” << endl;
70
cin
 The standard input by default is the keyboard and we will
now look at cin as the stream object to access what is to be
input.
int x;
cin >> x;
 The value of x can be entered.
 We will use both cin and cout in this example.
71
Example 9: cin and cout
Write a program that takes a number from user and print the entered number and
its double.
#include <iostream>
using namespace std;
int main ()
{
float x;
cout << “Please enter a number: ”;
cin >> x;
cout << “The value you entered is” << x;
cout << “and its double is” << x*2 << “.\n”;
return 0;
}
72
… Cont’d
 Like cout, one can chain cin to request more than one data in a
single line statement. For example:
cin >> x >> y;
 is equivalent to:
cin >> x;
cin >> y;
 Let us now look at an example where cin, cout is used to get a string
from the keyboard.
 When writing a console-based program in C++, cin might not
effectively capture the string.
 Therefore, we have to introduce a function called getline in the
example below:
73
… Cont’d
// Example 10: cin, cout, getline
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string x;
cout << “What’s your name?”;
getline (cin, x);
cout << “Hello” << x << “.\n”;
return 0;
}
74
… Cont’d
//Example 11: operating with variables // Example 12: increment operator
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main () int main()
{
{
int a, b;
int count = 10;
int result;
cout << “count=” << count << endl; //
a = 5;
cout << “count=” << ++count << endl; //(prefix)
b = 2;
a = a + 1; cout << “count=” << count << endl; //
result = a - b; cout << “count=” << count++ << endl; //(postfix)
cout<< result<<endl; cout << “count=” << count << endl;
return 0; return 0;
} }
75
Example
1. Write a C++ program that calculate the average, maximum,
minimum, and sum of three numbers given by the user.
2. Write a C++ program that find the area of a circle where the
radius is provided by the user.
3. Write a C++ program that solve quadratic equation.
4. Write a C++ program that converts temperature from Fahrenheit
degrees to Celsius degrees. use
5. Write a C++ program that takes a number from user to display
that number and it’s double.
A C++ program that takes a number from user to display that number and it’s double.
Source code Output

76
77
Exercise 3
3. Write the output of the following program.
1. Read an integer number of a fixed length (3
#include<iostream.h>
digits) from the standard input then print its void main()
digits separated by spaces. For example if {
int x=10,y=20,z=30;
364 is the input then the output should be 3 6 4
--x;
or 4 6 3. y=++y;
z=x--;
2. Write a program in C++, which takes radius
cout<<”x= ”<<x<<endl;
from the user and calculate the area and cout<<”y= ”<<y<<endl;
circumference of a circle. cout<<”z= ”<<z<<’\n’;
cout<<x+y;
}
78
… Cont’d
5. What is the output of the following program
4. You can convert temperature from degrees #include<iostream.h>
int main(){
Celsius to degrees Fahrenheit by multiplying int x,y, c=10;
cout<<c++;
by 9/5 and adding 32. Write a program that x=2*c+1;
cout<<'\n'<<x;
allows the user to enter a floating-point y=--x+1;
cout<<'\n'<<y;
number representing degrees Celsius, and
x=c++;
cout<<'\n'<<x;
then displays the corresponding degrees
cout<<'\n'<<c++;

Fahrenheit. x=2*x++;
cout<<'\n'<<x;
cout<<'\n'<<4+x;
return 0;
}

You might also like