You are on page 1of 19

Chapter-2

Fundamental of C++ program

Basics of programming

What is a program?

To restate the definition, a program is just a sequence of instructions, written


in some form of programming language that tells a computer what to do, and
generally how to do it. Everything that a typical user does on a computer is
handled and controlled by programs. Programs can contain anything from
instructions to solve math problems or send emails, to how to behave when a
character is shot in a video game. The computer will follow the instructions of a
program one line at a time from the start to the end.

Types of programs

There are all kinds of different programs used today, for all types of purposes.
All programs are written with some form of programming language and C++
can be used for in any type of application. Examples of different types of
programs, (also called software), include:

Operating Systems

An operating system is responsible for making sure that everything on a


computer works the way that it should. It is especially concerned with making
certain that your computer's "hardware", (i.e. disk drives, video card and sound
card, and etc.) interfaces properly with other programs you have on your
computer. Microsoft Windows and Linux are examples of PC operating systems.
Office Programs
This is a general category for a collection of programs that allow you to
compose, view, print or otherwise display different kinds of documents. Often
such "suites" come with a word processor for composing letters or reports, a
spreadsheet application and a slide-show creator of some kind among other
things. Popular examples of Office Suites are Microsoft Office and
OpenOffice.org
Web Browsers & Email Clients
A web-browser is a program that allows you to type in an Internet address and
then displays that page for you. An email client is a program that allows you to
send, receive and compose email messages outside of a web-browser. Often
email clients have some capability as a web-browser as well, and some web-
browsers have integrated email clients. Well-known web-browsers are Internet
Explorer and Firefox, and Email Clients include Microsoft Outlook and
Thunderbird. Most are programmed using C++, you can access some as Open-
source projects, for instance (http://www.mozilla.org/projects/firefox/) will
help you download and compile Firefox.
Audio/Video Software
These types of software include media players, sound recording software,
burning/ripping software, DVD players, etc. Many applications such as
Windows Media Player, a popular media player programmed by Microsoft, are
examples of audio/video software.
Algorithm Development
Once the requirements of a program are defined algorithm development is the
next step. An algorithm is a finite set of well defined rules for the solution to a
problem in a finite number of Steps.
To design an algorithm for a specific problem first we break down the problem
in to simpler and manageable tasks. For one problem there may be a lot of
algorithms that help to solve the problem. An algorithm needs to be
 Precise and unambiguous (no ambiguity in any instruction and in the
order of execution)
 Simple
 General (one inch is equal to 2.54cm is not an algorithm, it has to
convert a supplied number of inches)
 Correct
 Finite (has to have an end)
 Handles all exceptions
 Produce expected output
 Efficient: in time, memory and other resources
An algorithm can be expressed in many ways. Some of these methods are:
i) Narrative: often used to narrate the algorithm, can be understood by any
user who may not have any knowledge of computer programming. Too wordy,
too ambiguous and can be interpreted in different ways.
ii) Structured English: uses English to write operations in a group. For
example,
1. Compute gross pay
2. Add one to counter
3. Multiply hours worked by pay rate to get gross pay
4. Get master record
5. Move field to output record
iii) Pseudo-code: similar to real code. For example consider the following code
which
Calculates grade based of the given mark.
IF Mark>80
Grade<--A
ELSE IF Mark>=70
Grade<--B
ELSE IF Mark>=60
Grade<--C
ELSE IF Mark>=50
Grade<--D
ELSE
Grade<--F
ENDIF
iv) Flowcharts: A flowchart consists of an ordered set of standard symbols
(mostly geometrical shapes) which represent operations, data flow or
equipment. The standard Flowchart symbols and their meaning are given
below.

Here are a few rules:


a. Every flowchart has a START and STOP symbols
b. The flow of sequence is generally from the top of the page to the bottom of
the page. This can vary with loops which need to flow back to an entry point
c. Use arrow-heads on connectors where flow direction may not be obvious
d. There is only one flow chart per page
e. A page should have a page number and a title
f. A flow chart on one page should not break and jump to another page
g. A flow chart should have no more than around 15 symbols (except start and
stop symbols).
Example 1:
Write an algorithm to add two numbers and display their result. Also draw a
flowchart.
Structured English (Algorithm Description)
1. Read the rules of the two numbers a and b
2. Assign the sum of a and b to c
3. Display the result c
Pseudo code
1. Start
2. Declare variables a, b, c
3. READ a and b
4. C = a + b
5. Display c
6. Stop
Flowchart for above example
Start

Declare A, B, C

Read A, B

C = A+B

Write C

Stop
Basics of C++
The following simple C++ program demonstrates the basic structure of C++
programs.
//include headers; these are modules that include functions that you may use
in your
//program; we will almost always need to include the header that
// defines cin and cout; the header is called iostream.h
#include <iostream.h>
int main() {
//variable declaration
//read values input from user
//computation and print output to user
return 0;
}
After you write a C++ program you compile it; that is, you run a program called
compiler that checks whether the program follows the C++ syntax:
 if it finds errors, it lists them
 If there are no errors, it translates the C++ program into a program
in machine language which you can execute
Notes
What follows after // on the same line is considered comment indentation is
for the convenience of the reader; compiler ignores all spaces and new line; the
delimiter for the compiler is the semicolon
 all statements ended by semicolon
 Lower vs. upper case matters!!
 Void is different than void
 Main is different that main
Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing.
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:
// line comment
/* block comment */
The first of them, known as line comment, discards everything from where the
pair of slash signs (//) is found up to the end of that same line. The second
one, known as block comment, discards everything between the /* characters
and the first appearance of the */ characters, with the possibility of including
more than one line. Adding comments to our program may make it look like:
/* my second program in C++
with more comments */
#include <iostream.h>
int main ()
{
cout << "Hello World! "; // prints Hello World!
cout << "I'm a C++ program"; // prints I'm a C++ program
return 0;
}
Program Output: Hello World! I'm a C++ program
Program Errors
Syntax errors
 Violation of the grammar rules of the language
 Discovered by the compiler
 Error messages may not always show correct location of Errors
Example:
#include <iostream>
using namespace std
int main()
{
cout << "Programming is fun << endl;
return 0;
}
Run-time errors
 Error conditions detected by the computer at run-time
Example:
#include <iostream>
using namespace std;
int main()
{
int i = 4;
int j = 0;
cout << i / j << endl;
return 0;
}
Here, i and j are called variables. i has a value of 4 and j has a value of 0. i / j
in line 8 causes a runtime error of division by zero.
Logic errors
 Errors in the program’s algorithm
 Most difficult to diagnose
 Computer does not recognize such an error
Example:
#include <iostream>
using namespace std;
int main()
{
cout << "Celsius 35 is Fahrenheit degree " << endl;
cout << (9 / 5) * 35 + 32 << endl;
return 0;
}
Celsius 35 is Fahrenheit degree
67
Escape Character
The backslash (\) is called an escape character. It indicates that a “special”
character is to be output. When a backslash is encountered in a string of
characters, the next character is combined with the backslash to form an
escape sequence. Some common escape sequences are
Escape Sequence Meaning
\n .......................................................New line
\t ........................................................Horizontal Tab
\v .......................................................Vertical tab
\b ......................................................Backspace
\' ................................................ Single quote (')
\" .............................................. Double quote (")
\? ..............................................Question mark (?)
\\ ...............................................Backslash (\)

Example: Write a program that displays the following


Abebe 25
Zerihun 30
Frehiwot 27
Chala 31

#include <iostream>
usingnamespace std;
int main (){
cout << “Abebe”<<”\t”<<25<<endl;
cout << “Zerihun”<<”\t”<<30<<endl;
cout << “Frehiwot”<<”\t”<<27<<endl;
cout << “Chala ”<<”\t”<<31<<endl;
}
Variable declaration and initialization
Basic Data Types
C++ supports a large number of data types. The built in or basic data types
Supported by C++ are integer, floating point and character. C++ also provides
The data type bool for variables that can hold only the values true and false.
Some commonly used data types are summarized in table along with
description.
Type Description
Int Small integer number
long int Large integer number
float Small real number
double Double precision real number
long double Long double precision real number
char A Single Character
bool Stores either value true or false.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables
the compiler to make available the appropriate type of location in the memory.
float total;
You can declare more than one variable of same type in a single statement
int x, y;
Example:
// operating with variables
#include <iostream>
usingnamespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
Initialization of variable
Variable is a location in the computer memory which can store data and is
given a symbolic name for easy reference. The variables can be used to hold
different values at different times during the execution of a program.

When we declare a variable its default value is undetermined. We can declare a


variable with some initial value.
int a = 20;
Example :
// initialization of variables
#include <iostream>
usingnamespace std;
int main ()
{
int a=5; // initial value: 5
int b(3); // initial value: 3
int c{2}; // initial value: 2
int result; // initial value undetermined
a = a + b;
result = a - c;
cout << result;
return 0;
}

Constants
A variable which does not change its value during execution of a program is
Known as a constant variable. Any attempt to change the value of a constant
Will result in an error message. A constant in C++ can be of any of the basic
Data types, const qualifier can be used to declare constant as shown below:
const float PI = 3.1415;
The above declaration means that PI is a constant of float types having
a value 3.1415.
Examples of valid constant declarations are:
const int RATE = 50;
const float PI = 3.1415;
const char CH = 'A';

Operators
Operators are special symbols used for specific purposes. C++ provides six
Types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators,
Assignment operators, Conditional operators, Comma operator
Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic
(Numeric) operation. You can use the operators +, -, *, and / with both integral
And floating-point data types. Modulus or remainder % operator is used only
With the integral data type. Operators that have two operands are called binary
operators.
Relational operators
The relational operators are used to test the relation between two values. All
Relational operators are binary operators and therefore require two operands. A
Relational expression returns zero when the relation is false and a non-zero
When it is true. The following table shows the relational operators.
Relational Operators Meaning
< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to

Logical operators
The logical operators are used to combine one or more relational expression.
The logical operators are
Operators Meaning
|| OR
&& AND
! NOT
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This
Operator takes the expression on its right-hand-side and places it into the
Variable on its left-hand-side.
For example:
m = 5;
The operator takes the expression on the right, 5, and stores it in the variable
On the left, m.
x = y = z = 32;
This code stores the value 32 in each of the three variables x, y, and z.
In addition to standard assignment operator shown above, C++ also support
Compound assignment operators.
Compound Assignment Operators
Operator Example Equivalent to
+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ =2 A=A/2
*= A*=2 A=A*2

Increment and Decrement Operators


C++ provides two special operators viz '++' and '--' for incrementing and
Decrementing the value of a variable by 1. The increment/decrement operator
Can be used with any type of variable but it cannot be used with any constant.
Increment and decrement operators each have two forms, pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x, y;
int i = 10, j = 10;
x = ++i; //add one to i, store the result back in x
y = j++; //store the value of j to y then add one to j
cout << x; //11
cout << y; //10

Input and output


Standard Input Stream (cin)
cin can be used to input a value entered by the user from the keyboard.
However, the extraction operator >> is also required to get the typed value
from cin and store it in the memory location.
Let us consider the following program segment:
int marks;
cin >> marks;
In the above segment, the user has defined variable marks of integer type in
the first statement and in the second statement he is trying to read a value
from the keyboard.
Example 1:
// input output example
#include <iostream>
using namespace std;
int main ()
{
int length;
int breadth;
int area;
cout << "Please enter length of rectangle: ";
cin >> length;
cout << "Please enter breadth of rectangle: ";
cin >> breadth;
area = length * breadth;
cout << "Area of rectangle is " << area;
return 0;
}
Output :
Please enter length of rectangle: 6
Please enter breadth of rectangle: 4
Area of rectangle is 24
Example 2:
include <iostream>
usingnamespace std;

int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}

Standard Output Stream (cout)


Data is often output to cout which is normally the computer screen, but cout
can be redirected to another device. When we say that a program prints a
result, we normally mean that the result is displayed on a screen. Data may be
output to other devices, such as disks and hardcopy printers.

cout <<"Hello"; // prints Hello


cout << Hello; // prints the content of variable Hello
cout <<"Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the value of x on screen

#include<iostream>
using namespace std;

int main()
{
int a,b,c;
cout<< "\nEnter first number : ";
cin>>a;
cout<<"\nEnter second number : ";
cin>>b;
c=a+b;
cout<<"\nThe Sum is : "<<c;

return 0;
}

Enter first number: 81


Enter second number: 93
The Sum is: 174

Review exercise
1. Write an algorithm, draw flowchart for the following questions (some of
these examples will be done in class) and display the result on screen
a. Check a number is negative or not.
b. Find the largest among three different numbers entered by user
d. Factorial of a number entered by the user.
e. Find the Fibonacci series till term <=1000.
f. Sums all the even numbers between 1 and 20 inclusive.
2. What do you understand by expression ‘ # include <iostream>’ in a program
?

3. What is wrong with following statements? Also give the correct version.
(a) int x = 6.75;
(b) int shot = 8;
(c) char m = A;

(d) double n = int (B);

4. Find errors in following declarations and write the correct versions.


(i) Int n ;
(ii) int 8 = n;
(iii) char ch = a ;
(iv) Char alpha = A;

(v) Double M = 6.78;

5. Find errors in the following program. Rewrite a correct version of it.


include <iostream>
int main ()
int n , m ;
{
n = m + 4;
m = 5.5;
cout << m << “ “n<< endl;
cout >> m*m <<endl;
}

6. Explain the difference between pre and post increments, i.e. ++ n and n++.
7. Evaluate the following for int n = 8 ;
(a) ++n += 3;
(b) –n % 3 += 2;
8. Evaluate the following for int n = 4;.
(a) ++n*n++;
(b) ++n*n– – ;
(c) 2*++n + 3 * – –n;
(d) ++n += 3;
9. Evaluate the following expressions for int n = 20 ;
(a) n /= 5;
(b) n += 8;
(c) n %= 7;

10. Determine the output of following program.

#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
int m = 6,n = 2, a=0,b=0,c=0,d=0,e=0;
a +=4 + ++m*n ;
b *=3+ -m*m ;
c +=2 +m *++m ;
d *=2* + m*m-- ;
e -=2*++m / m-- ;
cout<<“a = “<<a<<“, “<<“b = “ << b<<“, c = “<<c<<“, d
= “<<d <<“, e = “<<e <<endl;
return 0 ;
}

11. Determine the output of following program.

#include <iostream>
using namespace std;
int main (){

int m=3, n=4, p=5, s=6, q=31;

m += 2;
n *= 4;
p –= 3;
s /= 2;
cout <<“m = ”<<m <<“, n = ”<<n<<“, p = ”<<p<<“, s = ”
<<s<<endl;
q %= 4 + (n /= 4);
cout << “ q = “ << q << endl;
return 0;
}

You might also like