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

Chapter 3

This document discusses basic C++ programming concepts including: 1. Syntax, functions, libraries, library functions, and statements which are the basic building blocks of a C++ program. 2. The structure of a basic "Hello World" program including comments, preprocessor directives, functions, and output statements. 3. Variables, data types, and constants which allow programs to store and manipulate different types of data. Variables represent memory locations that can store values, while data types specify what kind of values a variable can hold.

Uploaded by

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

Chapter 3

This document discusses basic C++ programming concepts including: 1. Syntax, functions, libraries, library functions, and statements which are the basic building blocks of a C++ program. 2. The structure of a basic "Hello World" program including comments, preprocessor directives, functions, and output statements. 3. Variables, data types, and constants which allow programs to store and manipulate different types of data. Variables represent memory locations that can store values, while data types specify what kind of values a variable can hold.

Uploaded by

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

CHAPTER 3: C++ PROGRAMMING BASICS

Terms used in this chapter

Syntax:
In the study of human languages, syntax is the part of grammar which deals with the construction
of sentences
• arrangement of words

• the relation between the words

In C++, syntax is the language structure that allows us to combine the C++ vocabulary of
commands into a program. In short, C++ syntax is the correct way of putting C++ vocabulary
together to perform something. When you have a syntax error, it means that you have not put them
correctly.

Function:
A named unit of code that performs a task

(Standard) Library:
A code that is available with the compiler. It contains a rich set of capabilities needed by
programmers.
Example: Outputting to the screen, performing mathematical operations

Remember: The computer hardware can only perform simple tasks (arithmetic, logical and shift
operations), the rest has to be programmed using these simple operations.

Library Functions:
Functions found in a library

Statements:
The instructions in a program

3.1. The Visual Studio IDE (covered in the lab) 3.2. Basic
Program Construction
This was the program observed in the laboratory

Page 1 of 46
1. #include <iostream.h>
2. int main ()
3. {
4. cout<<"Hello World! \n";
5. return 0;
6. }
Line 1: The #include preprocessor directive
This line tells the compiler that our code will be making use of the iostream.h library. All the
capabilities of this library are mentioned in the file "iostream.h". The compiler has a set of
locations in the hard disk where it looks for these flies: known as header files. All lines that begin
with the "#" sign are known as preprocessor directives. These are lines that tell the compiler
something (more on this later).

In effect, the #include directive is replaced by the contents of the file indicated.

Syntax:
#include <filename>

Note: You can include as many libraries as you like in your program. Each directive must be
placed on a new line
Typical programs that we will use in this course, may have the following directives
1. #include <iostream.h>
2. #include <math.h>
3. #include <iomanip.h>
4. #include <string.h>

Note: Lafore and other books use Standard C++. We will see more of this later. In these books we
have something like
1. #include <iostream.h>
2. using namespace Std;
There is no .h after the library name and there is one additional line as shown. For now, assume
that this produces the same results as above.

Page 2 of 46
Lines 3 7: The main function
Line 3 is the beginning of the main function. This line states the name of the function and a few
other things that we will see later. The whole function includes everything within the curly braces:
known as the "function body".
The operating system runs our programs starting from the function called main. This function does
whatever it is supposed to do (line 5, in this case) and returns a value to the operating system. (line
6). The operating system uses this value to determine whether our program succeeded or failed.

Note: There must be a function called main in your program. No main means error. We will see
more about functions in later chapters.

Syntax: (for now)


int main ()
{
our code
return 0;
}
Line 5: The output statement
This statement causes the phrase within quotation marks to be displayed to the user. cout
(pronounced as see out), predefined in iostream.h, corresponds to the standard output stream. The
standard output stream is normally the screen.
A stream indicates flow of data. In this case, data flows to the output stream.

Simple Syntax:
cout<<object to be outputted

cout represents the output stream


<< insertion operator puts the object on its right side to the object on its left side.
"Hello World! \n" string literal. Represents a value cout
usage to be investigated in the lab.
Note that the two instructions,
5. cout<<"Hello World! \n"; 6. return 0;
end with a semicolon. A semicolon signals the end of a statement. This is a very important part of
the C++ syntax but one that is easy to forget.

Page 3 of 46
White Space
Our program is structured in such a way as to make it readable. It contains lots of spaces and
newlines, most of which are not important. They are just there to make the code readable. They
are known as "whitespaces" (spaces, carriage returns, line feeds, tabs, vertical tabs, form feeds).
The C++ compiler ignores whitespaces. Therefore, they can be added and removed as deemed
necessary. However, care must be taken to identify the important spaces in the code. This is to be
demonstrated in the laboratory.

For example, all these programs are valid

1. #include <iostream.h>
2. int main () {cout
3. <<
4. "Hello World! \n"
5. ;
6. return
7. 0
8. ;}

1. # include<iostream.h>
2. int main () {cout<<"Hello World! \n"; return 0;}
1. #include< iostream.h>
2. int main ()
3. {
4. cout << "Hello World! \n";
5. return 0;
6. }

But please, don't write like the above examples! This will confuse you and introduce errors that
you may not identify easily. Make sure that your code is always legible and well organized.

Page 4 of 46
Comments
It is relatively easier to try to understand what a program written in a high level language does by
simply reading the code (especially if the code is written in a well-structured manner see previous
topic). But sometimes even this task may be difficult as there are some things only the
programmer knows.
To assist a person reading your code in understanding what your program does, you usually leave
comments within the source code. The compiler ignores comments and therefore, they do not
affect your final program.
To leave single line comments in your code, precede them with // (two forward slashes).
Everything after the // and before the next new line is treated as a comment. To leave
block comments or multiline comments, enclose them within /* and */. Everything in
between these two is regarded as a comment.

Note: By default, Visual Studio 6 IDE highlights comments in green

Examples
1. /* Basic Program Construction Demo
2. Written on: March 24, 2009
3. Purpose: To demonstrate basic C++ program construction
4. */
5. //Filename: Basics.cpp
6.
7. #include <iostream.h> //Preprocessor directive.
8. //The above line tells the compiler to replace it with
9. //the contents of the file "iostream.h"
10.
11. int main ()//The function called "main". Must be present
12. {
13. //The following line is the first piece of code to
14. // be executed in our program
15. cout /*the output stream*/ << "Hello World!\n";
16. /* notice the semicolon it marks the
17. end of a statement */

Page 5 of 46
18. return 0; //Tell the OS Success!
19. }
Comments are almost always a good thing.
Remember that:
• People reading your code may need explanation (for example, me, the teacher, correcting your
assignment)
• You may forget the key details of your program when you look at it, in say, 2 weeks! (this is
true!)
• Make sure the comments clarify your reasoning (the big picture). The details can be
understood from the source code

For example, for a person who understands C++, the following comment is unnecessary
12. cout<<4+3;
13. //The above line adds 4 and 3 and displays the result

The following comment is more helpful to the reader who wants to know why 4 and 3 are being
added
12. cout<<4+3;
13. //This calculates the number of days in a week

3.3. Variables, Data Types, and Constants


As mentioned in the first chapter, a program is a sum of its algorithms and its data. You have already
been introduced to data in the laboratory exercises.
Example:
"Hello World", 42, 3.14 ...

These types of data are known as literals or constants or literal constants. These are values that you
type into your program whenever needed.
Example from the lab:
cout<<"Name: Mohammed\n"
<<"Age: "<<26;

Now do the following mental exercise with me, do not write down anything
Page 6 of 46
1. Remember the number 6
2. Remember the number 3
3. Add 4 to the first number and remember the result
4. Subtract the second number from the result in step 3.
If you were allowed to write, you might write something like this
1. a = 6
2. b = 3
3. c = a+4 = 6+4 = 10
4. d= c b = 10 3 = 7

If you did this, then you used variables to represent the values.

Variable
A variable is a portion of the computer's memory, in which we can
store a value and from which we can later retrieve that value.
Each variable
• Has a symbolic name (identifier), Example a?
• Can be given a variety of values

Now remember our model of the computer's main memory

Data Types
Since a variable can be given any value, our computer and our program need a way of distinguishing
the type of value stored in a variable.
C++ defines a set of arithmetic types, which represent integers, fractional numbers, characters of the
alphabet and Boolean values.

The following table gives the names of these types, the number of bits used to store values of such
types, and the maximum and minimum possible values that can be stored into such variables.

Keywor Meaning Bytes Low High


d

Page 7 of 46
bool Boolean value 1 FALSE TRUE
char Character 1 128 127
short Short Integer 2 32768 32767
int Integer 4 2147483648 2147483647
long Long Integer 4 2147483648 2147483647
float Single precision floating point (fractional) 4 3.4x1038 3.4x1038
number
double Double precision floating point number 8 1.7x10308 1.7x10308
Note that
• the size of the types (number of bytes used) and as a result, the minimum and maximum
values stored varies from machine to machine. The values presented here may not be true for
all computers.
• because of the limitations of digital systems, numbers in computers are not exactly like
numbers in mathematics. For example, integers in mathematics can range from ∞ to +∞
whereas integers in computer systems can range from 232 to 2321.
• in fractional (floating point) numbers, we are more concerned with the precision than the
range. Single precision floating point numbers provide 7 digits of precision while double
precision floating point numbers provide 15 digits of precision.
• computers store data as a sequence of bits. It is ultimately the type that determines the
meaning of these sequence of bits.

Page 8 of 46
(The following note was taken from the book C++ Primer, 4th Edition by Stanley Lippmann)

Variables are usually defined with the following syntax: type


variable name;

Example:
int a; float c; char d;

Once declared, the variables can be used.

Example,
5. int a;
6. int b;
7. int c;
8. int d;
9. a = 6;

Page 9 of 46
10. b = 3;
11. c = a + 4;
12. d = c b;
13. cout<<” The result is: “<<d<<endl;
14. return 0;

Note that
• you must declare a variable before using it.
• variable declarations can be placed anywhere within the program.
• for readability purposes, variables are usually declared at the beginning of the main function.

Variable Names (Identifiers)


Our example program uses a, b, c, and d as variable names (identifiers). We can give any names to
our variables as long as we follow the following rules
1. You can use
◦ UPPERCASE and lowercase letters
◦ the digits from 1 to 9
◦ the underscore, _, symbol
2. You can't use a C++ keyword as an identifier
Keyword a predefined word with special meaning. The list of C++ keywords is given below.
Note that visual studio 6 IDE, by default, highlights keywords as blue.
3. An identifier cannot begin with a number
4. An identifier can be as long as you like. (there are some limitations but forget them for now)
5. C++ is case sensitive. That means, mohammed is not the same as Mohammed which is not the
same as MOHAMMMED.

Page 10 of 46
Exercise: Which of the following are valid identifiers
home1 while _4 Abiy
min_Age FOR 512 2ndAddress B.W four homeWrk_1, oldcurriculum
class my, Value your value __AFX_H__

More on Defining and Initializing Variables


A declaration is a statement that defines a variable. For example, the following lines define three
variables.

int carCount; float base price, last_selling_price, averageSellingPrice;

Each definition starts with a type specifier, followed by a comma separated list of one or more
identifiers. A semicolon terminates the definition. The type determines the amount of storage that
is allocated for the variable and the set of operations that can be performed on it. Note that by
using a comma separated list, we can define multiple variables in a single statement.

The definitions above, however, do not specify an initial value for the variable. That means, you
have no idea what the value in carCount is right after the declaration. But a definition may also
provide an initial value for the variable. There are two types of initialization: copy initialization
and direct initialization, which are shown in the example below.

int carCount (100); //direct initialization int carCount = 100; //copy-


initialization

Page 11 of 46
In both cases, carCount is initialized to 100. There are some minor differences between the two
forms that we will not explain here. From this point on, we will mainly make use of the copy-
initialization syntax.

Note that when we define a variable without an initializer, the system sometimes initializes the
variable for us. However, it is always safe to first initialize a variable before using it.

Exercise: Compile and run the following program a multiple number of times. What do you
observe?

5. int unInt;
6. float unFloat;
7. cout<<” Uninitialized int = “<<unInt<<endl
8. <<” Uninitialized float =” <<unFloat<<endl;
Signed and Unsigned Types
The integral types, except the Boolean type, may be either signed or unsigned. A signed type can
represent both negative and positive numbers (including zero), whereas an unsigned type
represents only values greater than or equal to zero.

The unsigned types are used when the quantities represented are always positive – such as when
representing a count of something – or when the positive range of the signed types is not quite
large enough.

The integers, int, short, and long, are all signed by default. To get an unsigned type, the type must
be specified as unsigned.

Example unsigned short person_Age; unsigned long POPULATION; unsigned int


bytes; unsigned bits; //this is the same as unsigned int.

Unsigned types can represent the same number of values as signed types, except that all these
values are now greater than or equal to zero. For example, the range of unsigned short is from 0
to 65,535.

Exercise: Run the following program and observe the results. Can you explain them?

5. short magical;
Page 12 of 46
6. unsigned short not magical;
7. not magical = 42000;
8. magical = 42000;
9. cout<<” Magical = “<<magical<<” \nNot Magical =
“<<not magical<<endl;
10. unsigned short more magical = not_magical*2;
11. cout<<” More Magical = “<<more_magical<<endl;
12. unsigned short even_more_magical = 1;
13. cout<<” Even More Magical = “<<even_more_magical<<endl;

Note: The concept of a number being signed or unsigned is not valid for floating point types.

Literal Constants
A value, such as 100, in a program is known as a literal constant: literal because we can speck of
it only in terms of its value; constant because its value cannot be changed. Every literal has an
associated type. For example, 100 is an int and 3.14159 is a double.

Integer Literals
We can write a literal integer constant using decimal (base 10), octal (base 8), or hexadecimal
(base 16) notations. Those that begin with a leading 0 (zero) are interpreted as octal; those that
begin with either 0x or 0X are interpreted as hexadecimal.
Example:
15 //decimal
017 //octal
0xF //hexadecimal
All of the above represent the same number.

By default, the type of a literal integer constant is either int or long. By adding a suffix, we can
force the type of a literal integer constant to be type long or unsigned or unsigned long. We can
specify it is long by adding either 'L' or 'l' and that it is unsigned by adding either 'U' or 'u'. It is
better not to use lowercase 'l' for long as it looks the same as the number '1'. No space appears
between the number and the suffix.

Page 13 of 46
Example
23u /*unsigned */ 2000UL /*unsigned long */
42L /* long */ 87Lu /*unsigned long */
Note: There are no literals of type short.

Floating-point Literals
We can use either common decimal notation of scientific notation to write floatingpoint literal
constants. Using scientific notation, the exponent is indicated either by E or e. By default,
floatingpoint literals are type double. We indicate single precision by following the value with
either 'F' or 'f'. Each pair of literals below denote the same value
3.14159F .001f 0.
3.14159E0f 1e3F 0E0
Note: C++ provides a type known as long double (rarely used). A literal of this type is indicated
by adding the 'L' suffix. For example, 12.34L.

Boolean Literals
The words true and false are literals of type bool. Example:
bool is True = false;

Character Literals
Literals of type char are written by enclosing the character within single quotation marks. These
are printable characters. For example, 'a' '2'
',' ''

Some characters are nonprintable. A nonprintable character is a character for which there is no
visible image, like a backspace or a control character. Other characters have special meanings in
C++, such as the single and double quotation marks, and the backslash. These characters are
written using an escape sequence. An escape sequence begins with a backslash. C++ defines the
following escape sequences:
newline \n horizontal tab \t
vertical tab \v backspace \b
carriage return \r formfeed \f
alert(bell) \a backslash \\
question mark \? single quote \'

Page 14 of 46
double quote \” null character \0
Character String Literals
All of the literals seen so far have primitive built-in types (the types defined by C++ and listed on
the table on page 6). String literals are more complicated and are to be fully understood during the
discussion in Chapter 5.

String literal constants are written as zero or more characters enclosed in double quotation marks.
Non printable characters are represented by their underlying escape sequence. Examples:
“Hello World!”
“\nMy name is:\t”

String literals in C++ have one character in addition to those typed in by the programmer. Every
string literal ends with a null character (\0) added by the compiler.

Note that a character literal, 'A', represents a single character A, whereas “A” represents a string
literal containing the letter A and the null character.

The const Qualifier


Literal constants are great at specifying values that do not change (42 is 42 today and will be 42
tomorrow). Sometimes, the need may arise to represent a constant by a variable. This variable
must not be modified inside your program. C++ defines the const qualifier that precedes the data
type in a variable definition. It specifies that the value of the variable will not change throughout
the program and any attempt to do so will generate an error.

5. float r, area, perimeter;


6. const float PI = 3.14159F; //PI is now a constant.
7. //It's value can't be changed
8. cout<<” Enter the radius of the circle: “;
9. cin>>r;
10. area=PI*r*r; perimeter=PI*2*r;
11. cout<<” Area of the circle with radius “<<r<<” is
“<<area
12. <<”. It\'s Perimeter is “<<perimeter<<endl;
13. PI = 3.14; //this will generate an error

Page 15 of 46
Question: Why bother with using a variable when we can simply place the literal constant in its
place everywhere in the code?
Exercise: Modify the above program so that it can calculate the areas and perimeters of 5 circles
whose radii are obtained from the user. Now change the precision of PI to 3.14 and recompile the
program. Then do the above two steps again use literal constants instead of the constant variable
PI.

Note: Since a const variable cannot be modified, it must be initialized when declared.

The #define Directive


Although this method is not recommended in C++, constants can also be specified using the
preprocessor directive #define. This directive sets up an equivalence between an identifier and a
text phrase. For example, the line
#define PI 3.14159
appearing at the beginning of your program tells the compiler that the identifier PI will be
replaced by the text 3.14159 throughout the program. However, you can't specify the data type of
the constant using #define, which can lead to problems in your program.

Automatic Type Conversions and Casts


It is quite common in your programs to write statements that mix different data types. For
example

5. int count = 100;


6. float avgWeight = 70F;
7. double totalWeight = count*avgWeight;
8. cout<<” Total weight in this room = “<<totalWeight<<endl;

Here a variable of type int is multiplied by a variable of type float to give a result of type double.
This program compiles without error.

Types are considered “higher” or “lower”, based roughly on the order shown below long
double > double > float > long > int > short > char (where > means higher than)

When different types are mixed in an expression, the lower type variable is converted to the
highertype variable automatically. Therefore, in the above example, count is converted to type

Page 16 of 46
float (temporarily) before being multiplied with avgWeight and the result (a float) is converted to
a double before being assigned to totalWeight.

These conversions normally take place without you having to worry much about them. However,
this may not always be true. There are cases where the programmer has to specify the type
conversions. For example, the compiler will generate a warning for the following program.

5. int result;
6. float a = 4.0;
7. result = a*3.56;
Here, we are trying to multiply a float with a double, resulting in a double value. When trying to
assign this value to result, the compiler notices that result is of type int which is lower than
double. The compiler will give a warning saying that the result will be 'truncated'.

To avoid this warning, the programmer has to tell the compiler that this conversion was
intentional by using a cast. These will be exercised in the laboratory

Exercises:
1. Which, if any, of the following are illegal? Incorporate them into a program and observe
a) 3.14e1L d) 3.14159UL

b) 1024f e) “Who \are you?”

c) “multiple line f) “\” Yes”, he said” comment”

2. Identify and correct the errors/problems in these program fragments, if any


a) int double PI = 3.14159;
cout<<” PI is”<<PI;
b) int age = 12, height = 15;
cout <<”Age: “<<age<<”\tHeight:“<<height<<endl;
c) const int I, j=0; int i; i = I;

d) int a=12, b=5;


float result = a/b;
cout<<result;

Page 17 of 46
3.4. Operators, Expressions and Statements

Although not formally, you have already been introduced to these concepts either in the previous
sections or in the laboratory sessions.

Statements
A statement is the smallest independent unit in a C++ program. It is analogous to a sentence in
natural language. Statements in C++ generally end in semicolons. Our programs, generally, are
sequences of statements.

Expressions
Any arrangement of variables, constants and operators that specifies a computation is called an
expression. Thus 3.14, 42+3, and val1*(23+ val1) are expressions. When the computations
specified in the expression are performed, the result is usually a value. If the value of val1 is 1,
the results of the above expressions are 3.14, 45, and 24, respectively.

Parts of expressions may also be expressions. In the above example, 23+val1 is an expression.
Even single variables and constants, like 3.14 and val1, are considered to be expressions.

There are two kinds of expressions in C++:


Lvalues: An expression that is a lvalues may appear as either the left-hand or right hand of an
assignment.
Rvalues: An expression that is a revalues may appear on the right but not on the lefthand side of
an assignment.

Variables are lvalues and so may appear on the lefthand side of an assignment. Literal constants
are rvalues and so may not be assigned. Const variables are unmodifiable lvalues and may not be
assigned. The results of most operators are rvalues.

Arithmetic Operators
You have already been introduced to the arithmetic operators in the laboratory. The following
table summarizes the arithmetic operators.

Operator Name Usage


+ unary plus + expr
unary minus expr

Page 18 of 46
* multiplication expr1*expr2
/ division expr1/expr2
% remainder expr1%expr2
(modulus)
+ addition expr1+expr2
subtraction expr1expr2
Note: expr stands for any expression to be operated on by the operator. The term operand is also
used.

The unary minus operator, obviously, negates its operand. The unary plus makes no change to its
operand.

The +, , *, and / operators are closely analogous to their counterparts in algebra. Division between
integers results in an integer. If the quotient contains a fractional part, it is truncated.

int example = 10/3; //example equals 3, remainder truncated


int example2 = 9/3; //example2 equals 3, no remainder
The % operator is known as the remainder or modulus operator. It computes the remainder of
dividing the lefthand operand by the right-hand operand. This operand can be applied only to
operands of the integral types.

int example3 = 10%3; //example3 equals 1, the remainder

The unary operators have the highest precedence, then the multiplication and division operators,
then the remainder operator, and then the binary addition and subtraction operators. These
operators are all left associative, meaning that they are evaluated from left to right when the
precedence levels are the same. For example, by applying the precedence rule to the expression 5
+ 10*20/2, the operations are performed in the following order. (more on this later)
10*20 (result = 200)
200/2 (result = 100)
5 + 100 (result = 105)

Relational and Logical Operators


The relational and logical operators return values of type bool. They are used to test certain
conditions to find out whether they are true or not. They are summarized in the table below.
Page 19 of 46
Operator Name Usage
! Logical Not !expr
< Less than expr1 < expr2
<= Less than or equal expr1 <= expr2
> Greater than expr1 > expr2
>= Greater than or equal expr1 >= expr2
== Equality expr1 == expr2
!= Inequality expr1 != expr2
&& Logical AND expr1 && expr2
|| Logical OR expr1 || expr2
The logical operators treat their operands as conditions. The operand is evaluated and if the result
is zero, the condition is false, otherwise it is true. The overall result of the AND operator is true if
and only if both its operands evaluate to true. The logical OR operator evaluates to true if either
of its operands evaluates to true.

The logical AND and OR operators always evaluate their left operand before the right. The right
operand is evaluated only if the left operand doesn't determine the result. This evaluation strategy
is often referred to as “shortcircuit evaluation”.
The logical NOT operator (!) treats its operand as a condition. It yields a result that has the
opposite truth value from its operand. If the operand evaluates as nonzero, then! returns false.

The relational operators (<, <=, >, >=, ==, ! =) compare two operands. They return true if the
condition for comparison is fulfilled and false otherwise. We will see more of these operators in
later chapters.

Bitwise Operators
The bitwise operators take operands of integral type. These operators treat their integral operands
as a collection of bits, providing operations to test and set individual bits. These operators will not
be discussed now.

Assignment Operators
The lefthand operand of an assignment operator (=) must be a nonconst lvalue. Example:
int i, j, ival;

Page 20 of 46
const int ci = i; // ok: initialization not assignment 1024 = ival; // error: literals are
rvalues
i + j = ival; // error: arithmetic expressions are rvalues ci = ival; // error: can't write to ci
– const lvalue
The result of an assignment is the lefthand operand and the type of the result is the type of the
lefthand operand. The value assigned to the lefthand operand ordinarily is the value that is in
the righthand operand. However, assignments where the types of the left and right operands
differ may require conversions that might change the value being assigned. Example:
int intVar = 0; //result: type int, value 0 intVar = 3.14; //result: type int,
value 3

An assignment returns an lvalue. Therefore, we can perform multiple assignments in a single


expression.
int a, b; a = b = 0; //both a and b assigned 0

Unlike the other binary operators, the assignment operators are right associative. We evaluate an
expression with multiple assignment operators from right to left.

Note: Do not confuse the assignment operator with the equality operator.

Compound Assignment Operators


Consider the following example
int sum = 0;
sum = sum + 10;
We often apply an operator to a variable and reassign the result to the same variable. Since this
kind of an operation is common (also for other arithmetic operations), C++ provides operators
that simplify the task.

The compound operators are of the form op= (where op is the operator)
a op= b means a = a op b
Therefore, a += b means a = a + b
a = b means a = a – b

a *= b means a = a * b

Page 21 of 46
a /= b means a = a / b

a %= b means a = a % b

Increment and Decrement Operators


C++ also provides other operators for convenience. The operation of adding or subtracting one
from a variable is so common in programming that there are operators to simplify the task. These
operators are the increment (++) and decrement () operators. There are two forms of these
operators: prefix and postfix. The prefix increment operation increments its operand and returns
the changed value as its result. The postfix version increments the operand but returns the copy of
the original unchanged value as its result.

int i = 0, j;
j = ++i; // j=1, i=1: prefix increment

j = i++; //j =1, i = 2: postfix increment

j = i; //j=1, i = 1: prefix decrement

j = i-- //j=1, i=0: postfix decrement

Note: the prefix version returns an lvalue, the postfix version returns an rvalue;

Interesting Fact: C++ obtained its name from applying the postfix increment operator to C
(another language that C++ is derived from)

Evaluating Compound Expressions


An expression with two or more operators is a compound expression. In a compound expression,
the way in which the operands are grouped to the operators may determine the result of the
overall expression. If the operands group one way, the result differs from what it would be if they
grouped another way. Precedence and associativity determine which part of the expression is the
operand for each of the operators in the expression. An operator with a higher precedence is
evaluated before operators of lower precedence. Operators also have associativity which
determines how operators at the same precedence level are grouped. The arithmetic operators, for
example, are left associative.

Page 22 of 46
We can override these rules by parenthesizing compound expressions to force a particular
grouping. Parenthesized expressions are evaluated by treating each parenthesized subexpression
as a unit and otherwise applying the normal precedence rules.

The following table summarizes the operators discussed so far. The list is in order of decreasing
precision.

Operators Associativity
Postfix increment and decrement (++, --) Right
Prefix increment and decrement (++, --) Right
!, + (unary plus), (unary minus) Right
*, /, % Left
+, (arithmetic) Left
<, <=, >, >= Left
!=, == Left
&&, || Left
+=, =, *=, /=, %=, =, Right
Note: These are not the only operators in C++. Check the reference materials for a more complete
list.

Exercises:
1. Using the above table, evaluate the following expressions
a) 4+7*6/3 5
b)15/3*34 (5+7)/6
c) ++23/3+3
2. Write a program to verify your answer for question 1.

Statement Classifications
Depending on their complexity, we can divide statements into the following categories

Expression Statements: are statements that compute expressions. The statement syntax is simply
an optional expression followed by a semicolon. For example
42; // Valid but pointless cout << 42; // More typical
x = y * z; // An assignment; // Null statement

Page 23 of 46
The null statement is a special case of expression statements.

Declaration Statements: are statements that declare variables. For example


int x, y, z=10;
Compound Statements: A compound statement is a sequence of zero or more statements enclosed
within curly braces. Also called a block. For example
{int x; cout<<x;}

3.5. Using Library Functions

In C++, we make extensive use of library functions to accomplish tasks. This section will serve as an
introduction to how to use library functions. We will see how to use some library functions without
getting into the details of their inner workings.

Mathematical Functions
The mathematical functions allow us to do mathematical operations. These operations include
raising a number to a certain power, computing the square root of a number, computing the cosine
of an angle, etc.... These functions are defined in the header file math.h (or cmath in standard C+
+). Therefore, to use these functions, we must first include this header file.

Example:
1. /* Program to calculate the square root of a number */
2. #include <iostream.h> //for cout and cin
3. #include <math.h> //for the sqrt () function
5. int main ()
6. {
7. double num, ans;
8. cout<<” Enter the number “;
9. cin>>num;
10. ans = sqrt(num); /*calculate the square root of
11. num and store the result in ans*/
12. cout<<” The square root of “<<num<<” is “<<ans<<endl;
13. return 0;
Page 24 of 46
14. }

The statement of interest is in line 10.


ans = sqrt (num);

sqrt is the name of the function that performs the square root operation. This function takes one
argument of type double and returns a result of type double. An argument is the input to the
function. It is placed inside the parenthesis following the function name. What the function
returns is its output. It is the result of processing the argument. In this case, the return value is the
square root of the argument. Returning a value means that the function expression takes on this
value, which can then be assigned to another variable, in this case ans.
When a function takes multiple arguments, they are separated by commas inside the parenthesis.
For example, the function computing the result of raising a certain number by another needs two
arguments.

ans = pow (3, 4);

This statement computes 3 raised to 4. Similarly, we can have the following

ans = cos(num); //calculates the cosine of num (radians) ans = sin(num); //the sine of
num ans = abs(num); //the absolute value of num ans = exp(num); //e raised to num
ans = log(num); //the natural logarithm (base e) of num ans = log10(num);//the
common logarithm (base 10) of num and so on.

IO Manipulators
IO manipulators are operators used with the insertion operator (<<) to modify or manipulate the
way data is displayed. We’ve already seen the endl manipulator which writes a new line character
and forces the output to be displayed.

Other IO manipulators, which take arguments, are defined in the iomanip.h (or iomanip.h in
standard C++) header file. We use these manipulators to control output formatting.

Here are the most commonly used manipulators.


• setw(n): Sets the minimum size of a field to n. Applies only to the next element applied to the
output.

Page 25 of 46
• left: Left justifies the output. Only useful after setw(n).
• right: Right justifies the output. Only useful after setw(n). (Default)
• setfill(ch): Only useful after setw(n). If a value does not entirely fill a field, the character ch
will be used to fill in the other characters.
• setprecision(n): Sets the number of digits printed to the right of the decimal point. This
applies to all subsequent floating point numbers written to that output stream.
• fixed: Uses fixed point notation for floatingpoint numbers
• scientific: Formats floatingpoint numbers in scientific notation.

The example code shown below


demonstrates the use of IO
manipulators to print data in columns.
The output is shown on the right.
Experiment with it by changing values.
Example:
Observe the output of the following program (this program uses standard C++)
1. #include <iostream.h>
2. #include <iomanip.h>
3. using namespace Std;
4. int main ()
5. {
6. cout<<"Columns Demonstration” <<endl;
7. //use setw (10) to create columns (fields) 10 characters’ wide
8. cout<<setw (10) <<"Column 1"<<setw (10)
9. <<"Column 2"<<setw (10) <<"Column 3"<<endl;
10. //second row, simple set of data
11. cout<<setw (10) <<1<<setw (10) <<2<<setw (10) <<3<<endl;
12. //third row, left aligned
13. cout<<left<<setw (10) <<4<<setw (10) <<5<<setw (10) <<6<<endl;
14. //fourth row, remaining space filled with *
15. cout<<setfill ('*’) <<setw (10) <<7
16. <<setw (10) <<8<<setw (10) <<9<<endl;
Page 26 of 46
17. //fifth row, floating point numbers:
18. //precision 3, right aligned and remaining spaces unfilled
19. cout<<setprecision (3) <<right<<setfill (' ‘) <<setw (10)
20. <<9.010023<<setw (10) <<9.020023<<setw (10) <<9.030023<<endl;
21. return 0;
22. }

Note: If you don't use standard C++, you may have to use iOS: left and iOS: right instead.

Exercises (Real life problems)


1. Write a program that prints a table showing the sin, cos, and tan values for the uncommon
angles (15, 20, 70, and 140). Make sure that the values are displayed only up to 4 significant
digits.
2. The general characteristics of a semiconductor diode can be defined by the following equation

ID=ISekVD/TK−1 where k = 11,600 K/V for Silicon, VD is the diode


voltage in Volts, TK is the temperature in Kelvins, IS is the saturation current in
Amperes, and ID is the diode current.
Write a program that accepts IS (ranging from 1015A up to 109A), VD (ranging from 0 to
1Volts) and TK (ranging from 50 °C to 150 °C) from the user and calculates ID.
3. Modify the above program to print a table for the voltages and currents for a given
temperature (obtained from the user). Take IS = 109A and calculate ID for VD = 0, 0.1, 0.2, …,
1V. Do these values agree with the diode curve you saw in electronics class?

Page 27 of 46
CHAPTER 4: PROGRAM FLOW CONTROL

In C++, by default, statements are executed sequentially. In reality, however, not many programs
execute all their statements in strict order from beginning to end. Most programs (like many
humans) decide what to do in response to changing circumstances. They may do one thing if some
condition is met or another if not (decisions). They may also have to do a certain action repeatedly
(looping). Therefore, C++ defines a set of flowofcontrol statements that allow statements to be
executed conditionally or repeatedly. (Remember the discussion on Algorithms and Flowcharts)

How many times a loop is executed, or whether a decision results in the execution of a section of
code, depends on whether certain expressions are true or false. These expressions typically involve
relational and logical operators observed in Chapter 3.

4.1. Decisions and Branching

A program may need to make a onetime decision which alters the sequential flow of execution and
causes a jump to another part of the program (branching). C++ provides us with the if statement and
the switch statement for these purposes.

The if Statement
An if statement has two forms: one with an else branch and one without. First let's see the plain if
(without the else branch).
Syntax:
if (condition) statement

The if keyword is followed by a condition in parenthesis. The condition is a test expression that
evaluates to a boolean value. The statement can be a single statement or a compound statement. If the
condition is true, the statement is executed. Otherwise, the statement is skipped, and execution
continues with the next statement (not shown above). Example:
5. unsigned short age;
6. cout<<” Enter your age:> “;
7. cin>>age;
Page 28 of 46
8. if (age < 17)
9. cout<<” You are too young\n”;
10. cout<<” Thank you” <<endl;

The figure above shows two sample interactions with the program. As you can see, when the user
entered the value 12, the expression age<17 evaluated to true. This caused the first output statement
to be executed. When the user entered the value 56, the expression age<17 evaluated to false. This
caused the first output statement to be jumped.

Similarly, we can execute a block of statements if the condition is satisfied.

Example:

3. int main ()
4. {
5. int Val;
6. cout<<” Enter an integer value:> “;
7. cin>>Val;
8. if (val%2 == 0) //val%2 will be zero if val is divisible by two
9. {
10. int quotient = Val/2;
11. cout<<val<<” is divisible by 2” <<endl;
12. cout<<” The quotient is “<<quotient<<endl;
13. }
14. return 0;
15. }

In the above example, notice the condition val%2 == 0. First the modulus operator is used to
calculate the remainder of a division by two. Then this remainder is compared to 0 with the equality
operator. All the statements from line 10 to 12 will be executed if this condition evaluates to true.

Note: Don't confuse the equality operator (==) with the assignment operator (=). The compiler won't
signal an error if you do. This will result in a very hard to find bug in your program.

Exercises:
1. In the above example, add one line between lines 7 and 8, modify them as follows to observe
how the program misbehaves.
7. cin>>val; new. int rem = val%2;
8. if (rem = 0)

Page 29 of 46
2. It is also a common mistake to forget the curly braces. See how the program behaves if you
remove the curly braces on lines 9 and 13.

It is usually the case that we want another statement to be executed if the condition evaluates to false.
The if statement allows for this kind of either or condition by providing the else clause.
Syntax:
if (condition) statement1
else statement2

Here, if condition evaluates to true, statement1 will be executed. If it evaluates to false,


statement2 will be executed. Both statement1 and statement2 can be compound statements.
Example:
5. unsigned short age;
6. cout<<” Enter your age:> “;
7. cin>>age;
8. if (age < 17)
9. cout<<” You are too young\n”;
10. else
11. cout<<” You are old enough\n”;
12. cout<<” Thank you” <<endl;

Note: the whole of the if...else construct is considered as a statement.


These two forms of the if statement can be represented using flowcharts as follows

Nested if...else statements


Notice that statement2 can be any statement, including an if...else statement. This allows us to take
more complex decisions.
Page 30 of 46
Example:
5. unsigned short age;
6. cout<<” Enter your age:> “;
7. cin>>age;
8. if (age < 17)
9. cout<<” You are too young\n”;
10. else
11. if (age<40)
12. cout<<” Don’t worry, you are still young\n”;
13. else
14. if (age<70)
15. cout<<” Still young at heart\n”;
16. else
17. cout<<” Are you sure that is your age? \n”;

Here, the output statement on line 9 will be executed if age is less than 17. If not, the if...else
statement on lines 11 to 17 will be executed. Again, if the condition age<30 is fulfilled (mind you,
now we know age is greater than or equal to 17), the statement on line 12 is executed. If not, the
if...else statement on lines 14 to 17 will be executed. And so on. By rearranging white spaces, we
have the following, more convenient, form.
8. if (age < 17) //age is the element of [0, 17)
9. cout<<” You are too young\n”;
10. else if (age<40) //age is the element of [17, 40)
11. cout<<” Don’t worry, you are still young\n”;
12. else if (age<70) //age is the element of [40, 70)
13. cout<<” Still young at heart\n”;
14. else //age is greater than or equal to 70
15. cout<<” Are you sure that is your age? \n”;

If age is less than 17, line 9 is executed. After line 9 is executed, lines 10 to 15 are jumped. But if age
is greater than or equal to 17, control jumps to line 10. And so on.

Although this is not a new syntax, let us formalize its usage Convenient Form:
if (condition1) statement1
else if (condition2) statement2
...
else if (conditionN1) statementN1
else statementN

Exercises:
1. Develop a program that tells students their grade based on the following scale.
Mark>90 A 90 ≥ Mark > 85 A
85 ≥ Mark > 82 B+ 82 ≥ Mark > 76 B
76 ≥ Mark > 70 C+ 70 ≥ Mark > 61 C
Page 31 of 46
61 ≥ Mark > 50 C 50 ≥ Mark > 43 D
Mark ≤ 43 F
Take Mark as an input from the user.
2. Develop a program that converts temperature from Celsius to Fahrenheit and vice versa based
on the user's preference.
(Hint: Display the following menu to the user)
Temperature Converter
1. for Celsius to Fahrenheit
2. for Fahrenheit to Celsius choice:>
3. Develop a four function calculator that can
perform addition, subtraction, multiplication and
division of two numbers. The program should ask
the user for a number, an operator, and another
number.

The switch Statement


Situations usually arise where deeply nested if...else statements (a lot of levels of if...else statements
within other if...else statements) have to be used to realize a certain logic. It is usually very difficult to
express our intended logic using such deeply nested if...else statements. Modifying such code is also
much harder to get right.

As an alternative method of choosing among a set of mutually exclusive choices, C++ provides
the switch statement. Syntax:
switch (variable)
{
case constant1:
statements
break;
case constant2:
statements
break;

case constantN:
statements break;
default:
statements
}

The keyword switch is followed by the switch variable to test in parenthesis. This variable should be
an integer or character variable. Curly braces then delimit a number of case statements. Each case
keyword is followed by a constant, which is followed by a colon. The data type of the case constants
should match that of the switch variable. When the value in the switch variable matches a constant in
one of the case statements, the statement immediately following the case will be executed until a
break is reached.

Page 32 of 46
The break keyword causes the entire switch statement to exit and control goes to the first statement
following the end of the switch construction. If the value of the switch variable doesn't match any of
the case constants, the statements immediately following the default keyword will be executed. The
default keyword is optional. If it is not present and no match is found, control passes to the end of the
switch without doing anything.

Example:
5. unsigned short key, ans;
6. float balance = 23.0F;
7. long PIN;
8. cout<<” **** The 904 Program ****\n”;
9. cout<<” Press 1 for recharge” <<endl
10. <<” Press 2 for balance” <<endl
11. <<” Press 3 to change password” <<endl
12. <<” Press 4 for missing claim” <<endl
13. <<” Press 0 to exit” <<endl;
14. cin>>key;
15. switch (key)
16. {
17. case 1:
18. cout<<” Your prepaid account is being recharged” <<endl;
19. break;
20. case 2:
21. cout<<” Your account balance is currently “
22. <<balance<<” birr.” <<endl;
23. break; 24.
24. case 3:
25. cout<<” Please enter your 8 digit PIN number:”
<<endl;
26. cin>>PIN;

Page 33 of 46
27. break;
28. case 4:
29. cout<<” Press 1 to claim missing:” <<endl;
30. cin>>ans;
31. break;
32. case 0:
33. cout<<” Please wait while your call is transferred.”
<<endl;
34. break;
35. default:
36. cout<<” Are you sure?” <<endl;
37. }
38. cout<<” Thank you for using ETC's 904. Please come
again!”;

Note: Don't forget the break statement after each case. Without it, control passes down (or “falls
through”) to the statements for the next case, which is usually not what you want. No break statement
is necessary after default, since we're at the end of the switch anyway.
4.2. Looping

A program may also need to execute a group of statements more than once. C++ provides us with the
while, do while, and for statements for performing repetitive tasks.

The while Loop Statement


A while statement repeatedly executes a statement if a certain condition is true. Syntax:
while (condition) statement

The while keyword is followed by the condition in parentheses. The


expression inside the parentheses is tested and if it has a true value,
the statement (the body of the loop) is executed. Again, the statement
can be a single statement or a compound statement. This cycle of
testing the condition and executing the statement in the body of the
loop is repeated until the expression in parentheses is false. Each
repetition is known as an iteration.

In the following example, the program keeps on asking the user for an
answer until the user enters 42. Example:
5. short ans=0; //notice the initialization
6. while (ans! =42)
7. {
8. cout<<”\nWhat is the ultimate answer?: > “;
9. cin>>ans;
10. }
11. cout<<”Well done! You have found the answer.”;

Page 34 of 46
The while loop is known as a pretest loop because it tests the condition before each iteration. Notice
that the variable ans is initialized to 0. If ans had been initialized to 42, the loop would never have
been executed. This is an important property of the while loop: the while loop will never iterate if the
test condition is false to start with.

Conversely, if the test condition never evaluates to false, the loop will never terminate.
This results in an infinite loop which will loop forever. For example, commenting out line 9 in the
above example will make the loop an infinite one. Also note that a semicolon right after the
parentheses will be treated as a null statement and might generate an infinite loop. Adding a
semicolon at the end of line 6 will create an infinite loop. In this case, lines 7 to 10 are not treated as
the body of the loop.
The do … while Loop Statement
There are cases where we may want to execute the body of the loop at least once before testing the
condition. In other words, there are times where we may need a posttest loop. This is where the do
… while loop comes in. Syntax:

do statement
while (condition);

Here we have the do keyword followed by a statement which is followed by the while keyword and
the test condition in parentheses. (Again, we can have a block of statements.) The do … while loop is
identical to a while loop except that it performs at least one iteration even if the condition is false
from the start. Also notice that there is a semicolon at the end after the parentheses.

The following program shows a typical usage of the do … while loop – a program with a menu
system. Notice that the test condition would evaluate to false if this had been a pretest loop. Example:
5. int ans=0; //ans initialized to 0
6. do {
7. cout<<”What would you like to do?\n”
8. <<”1. Display \”Hello World\”\n”
9. <<”2. Do something trivial\n”
10. <<”3. Display a random number\n”
11. <<”Enter your choice (0 to exit):> “;
12. cin>>ans;
13. cout<<”OK then!\n”;

Page 35 of 46
14. /*Normally, you would use a switch statement to
15. do what the user asked */
16. } while (ans!=0); //don't forget this semicolon

Counters
Sometimes it is important to keep track of the number of iterations a loop makes. The following
example prints the square of the numbers from 1 to 10 using a while loop. Example:
6. int num=1; //num initialized
7. cout<<setw(6)<<”Num.”<<setw(10)<<”Square”<<endl;
8. while (num<=10) //notice no semicolon here
9. {
10. cout<<setfill(' ')<<setw(6)<<num<<setw(10)
11. <<setfill('.')<<num*num<<endl;
12. num++; //num updated
13. }

In this example, num is being treated as a counter. It is initialized to 1 on line 6 and it is updated
(incremented) with every iteration of the loop on line 12. With this arrangement, in each iteration, the
value of num indicates the number of iterations done so far. Although we can work with counters
using both while and do … while loops, C++ has one that is ideal for working with counters – the for
loop.

Exercises:
1. Rewrite the above example program using a do … while loop and only one expression
statement inside the body of the loop.
2. Modify the programs you wrote for the exercises in Chapter 3 so that the user can perform the
tasks your programs do as many times as she wishes.

The for Loop Statement


The for loop is ideal for working with counters because it provides built in expressions that
initialize and update variables. Syntax:
for (initialization; condition; update) statement

Here we have the for keyword followed by three expressions in parentheses, separated by semicolons
(notice the absence of a semicolon after the update expression). The initialization expression is used
to initialize or assign a starting value to a variable (usually a counter). This is the first action
performed by the loop and it is done only once. The condition expression controls the loop just like
the conditions in the while and do … while loops – if it evaluates to true, the statement will be
executed. Note that the for loop is a pretest loop and checks the condition before each iteration. The
update expression is executed at the end of each iteration. It is usually used to modify the variable
initialized with the initialization expression (for example, increment a counter). Example:
5. cout<<setw(6)<<”Num.”<<setw(10)<<”Square”<<endl;
6. for (int num=1; num<=10; num++) //the for header
7. {
8. cout<<setfill(' ')<<setw(6)<<num<<setw(10)
9. <<setfill (‘.’) <<num*num<<endl;10. }

Page 36 of 46
The order of execution for the for loop is as follows
1. The initialization statement is executed once at the start of the loop. num is declared and
initialized to 1.
2. Then the condition is evaluated. If num is less than or equal to 10, go to step 3, otherwise
terminate the loop.
3. Execute the statement. Display num and the square of num.
4. Finally evaluate the update expression (increment num) and go back to step 2.

Note: The for header can omit any (or all) of the initialization, condition, and update expressions.
The initialization and update expressions can be made up of multiple expressions separated by
commas.
Examples:
int count=0;
for (count<10; count++) //no initialization cout<<” Counting: “<<count<<endl;

for (int i=0; ++i) //no condition: defaults to true – infinite loop
cout<<” i is: “<<i<<endl;

int ans=0;
for (ans! =42;) //no initialization and update
{
cout<<” What is the answer? :> “;
cin>>ans;
}

for (; ;) //no initialization, condition or update – infinite loop


cout<<” Oh yes! \n”;

for (int i=0, j=1; j<40 && i! =j; i++, j*=2) //multiple update and init. cout<<” i is: “<<i<<” \tj is:
“<<j<<endl;

(More examples discussed in class).

Exercise:
1. Analyze the following code segment.
int i, sum;
for (i=1, sum=0; i<100; i++, sum+=i);
cout<<sum<<endl;
2. Write a program that accepts a number from the user and calculates its factorial.
3. Write a program that averages numbers. The numbers are to be entered by the user and their
amount is not predetermined.

Nested Loops
Just like we did with if … else statements, it is also possible to put one loop inside another loop. The
first loop is called the outer loop and the one inside it is known as the inner loop. You can nest your
loops as much as you like. Example:
Page 37 of 46
5. for (int i=0; i<10; i++) //outer loop header
6. {//beginning of outer loop
7. for (int j=0; j<5; j++) //inner loop header
8. {//beginning of inner loop
9. cout<<j<<'\t';
11. } //end of inner loop
12. cout<<”: “<<i<<endl;
13. } //end of outer loop

In this example, the outer loop is controlled by the i variable and the inner loop is controlled by the j
variable.
Nested loops are used when, for each iteration of the outer loop, something must be repeated a
number of times. For example, consider summing up the scores for each course for each student.

Exercises:
1. Write a program (programs) that print the following triangle patterns. You can use only for
loops and use cout to output only one character at a time. Valid characters are '*', ' ' (space),
and '\n'.
a) * b) * c) * **
** ***
*** *** *****
**** **** *******
***** ***** *********
2. Modify the above program to print the patterns for any number of rows the user desires.
3. Write a program that averages a set of test scores for a group of students. (Inputs are: number
of students, number of scores for each student, scores for each student)

The continue and break Statements


The break statement can also be placed inside a loop. When it is encountered, the loop stops and
program jumps to the statement following the loop. Example:
5. int n;
6. int count = 0;
7. cout<<” Enter any number between 1 and 10 : “;
8. cin>>n;
9. while (count++ < 10)
10. {
11. cout<<count<<endl;
12. if (count==n)
13. break;
14. }
15.
16. cout<<” You entered “<<count;

• The break statement provides a way to bypass the loop condition and interrupt the loop
• In a nested loop, the break statement interrupts only the loop it is placed in.
Page 38 of 46
The continue statement, placed inside a loop, causes the loop to stop its current iteration and begin the
next one. All statements in the body of the loop that come after it are ignored.

Example:
5. int n, count=0;
6. cout<<” Enter a number between 1 and 10 :> “;
7. cin>>n;
8. while (count++ < 10)
9. {
10. if (count==10)
11. continue;
12. cout<<” You did not enter “<<count<<endl;
13. }

Choosing a Loop
The while loop is ideal for situations where a pretest loop is required, i.e., if you don't want to iterate
if the condition is false from the beginning.

The do...while loop is ideal for situations where a posttest loop is required, i.e., if you want the loop
to iterate at least once even if the condition is false from the beginning.

The for loop is ideal for situations where a counter variable is needed.

Note: All loops are quite sufficient on their own for any task.

Variable Scope
Normally, we expect a variable name to be a unique entity. However, C++ allows us to reuse a name
as long as it is used in different contexts. This context is known as a scope. A scope is a region of the
program and a name can refer to different entities in different scopes. Most scopes in C++ are
delimited by curly braces. Names are visible from their point of declaration until the end of the scope
in which the declaration appears.

Example:
1. #include <iostream.h>
2. using namespace std;
4. int main () //the name main is now visible from this point on
5. {//open curly brace marks the beginning of a scope (scope 1). 6. int a = 10; // the
name a is now visible from this point 7. // on upto the end of the scope 1.
8. for (int i=0; i<5; i++)
9. {//open curly brace – beginning of scope 2
10. int a=5, b=10; //visible until the end of scope 2
11. cout<<a; //the new a is preferred(used)
12. } //close curly brace – end of scope 2
13. cout<<a<<endl; //here the new a is not visible
14. cout<<b<<endl; //b is not visible error
15. return 0;

Page 39 of 46
16. }
When using loops with multiple statements in their bodies, new scopes are introduced.
Scopes nest, i.e. all variables declared in an outer scope are visible in an inner scope.
Hence, in the above example, the variable a defined on line 6 is visible inside the scope starting on
line 9. However, when a new variable with the same name is defined in a new scope on line 10, it
overrides the previous definition. So within scope 2, the name a refers to the variable defined on line
10.

The initialization expression inside the for loop header causes confusion. Where is the variable i
going to be visible? ANSI Standard C++ states that the variable i defined with the initialization
expression should only be visible within the body of the for loop (scope 2). By this definition, the
variable will only be visible from line 8 up to line 12. Some compilers choose to ignore this
restriction and the compiler that comes with Microsoft Visual Studio 6 is one of them. When
developing programs with MS Visual Studio 6, the variable i will be visible from its point of
declaration (line 8) to the end of scope 1.

4.3. Introduction to Functions

A function is a collection of statements that performs a specific task. A function performs some
computation and usually yields a result. A program may be broken into a set of manageable
functions, or modules. This is called modular programming. Real world programs can easily have
thousands of lines of code and unless they are modularized, they can be very difficult to modify and
maintain.

So far, you have created a function called main in every program. You have also made use of library
functions such as sin and setw. Now we will study the basics of functions so that we can create our
own that can be used like the library functions.

When creating a function, we write its definition. A definition has the following parts.
Name: a unique name for the function. Naming rules are the same as those for variables.
Parameter List: a list of variables that hold values being passed to the function.
Body: the set of statements that make up the function.
Return Type: the data type of the value being sent back from the function.

Example:

1. int main ()
2. {
3. cout<<” Hello World! \n”;
4. return 0;
5. }

On line 1: int indicates the return type, main is the name of the function, and the parameter list goes
between the parentheses (currently empty). Line 1 is known as the function header. Every statement
within the curly braces is regarded as the function body. The last statement within the function is
usually a special statement that returns the value computed by the function (line 4).
Page 40 of 46
The main function is a special function because it gets executed automatically when the program
starts. All other functions are executed when they are called. These calls are made by function call
statements. You have written function call statements when using library functions.

Example:

1. #include <iostream>
2. using namespace std;3.
4. void sayHello ()
5. {
6. cout<<” Hello from function! \n”;
7. }
8.
9. int main ()
10. {
11. cout<<” First Hello from main! \n”;
12. sayHello (); //a function call statement
13. cout<<” Back in main\n”;
14. return 0;
15. }
In this example, a simple function is defined. The function header on line 4 tells us that the function
has a return type of void, its name is sayHello and it has no parameter list. From this, we conclude
that it takes no arguments and does not return anything. Inside the function body, we have a single
statement that prints a message to the screen (line 6).

On line 12, we call the sayHello function. In this case, notice that the function call statement is simply
the function name followed by parentheses followed by a semicolon.

When the program is run, it starts executing from the main function. It goes on with normal
sequential program flow until the function call statement on line 12 is encountered. When this
happens, the program jumps to the called function on line 4 and starts executing it sequentially. When
it reaches the end of the function on line 7, it returns back to the main function and continues
executing from where it stopped, i.e. after the function call statement (line 13).

In general, whenever a function call statement is encountered inside a function, execution is


interrupted and control jumps to the called function. When the function finishes executing, control
jumps back to the calling function. The figure below illustrates this process. The solid arrows
represent execution flow and the dashed arrows represent jumps.

Function calls can also be hierarchical. Function 1 calls Function 2 which may call a third function
and so on. Also note that the function name must be defined before it can be used. In the example
code above the name sayHello is visible in main because it is defined before main.

Page 41 of 46
Passing Data to a Function
Earlier we have said that a function performs some computation and yields a result. When a function
is called, the caller can send values into the function. The function then performs its computation
based on its inputs. The values that are sent into the function are called arguments. You have already
seen how to send arguments to a function when you were using library functions. A parameter is a
special variable that holds a value being passed as an argument into a function. By using parameters,
you can define your own functions that accept data from the caller.

As an example, let us modify the sayHello function defined in the previous example.
void sayHello (int times) //one parameter – times
{
for (int i=0; i<times; i++)
cout<<”Hello from function!\n”; }
Notice the variable definition inside the parentheses – times is the parameter. Inside the function
body, the parameter controls how many times the message is displayed. The function can now accept
an integer value as an argument which will be copied into times when the function is called. The
function call statement is now modified as:
sayHello (5);
where the argument is placed inside the parentheses. This will cause the sayHello function to display
the message 5 times.

A function can accept multiple arguments separated by commas (seen previously). To create a
function that is able to do that, we define a number of parameters separated by commas in the
function header. Consider the following headers
void sayHello (int times, int num) float aOverB
(float a, float b)
int bigFunction(int N, float val1, double val2, float val3)
Obtaining the Result from a Function
A function returns the result of its computation to its caller using the return statement. It takes the
form return expr; where expr is an expression which when evaluated will have the type indicated by
the return type of the function. A return type of void indicates that the function will not return a
value. In such cases, the return statement is not necessary.
Page 42 of 46
When a function returns a value, the function call evaluates to the returned value. Therefore, a
function call can be placed anywhere an expression is needed. Consider the following function calls:
double num = sqrt (5.6); cout<<” Sin 30 = “<<sin (3.14159/6);
if (abs(sin(ang)*sin(ang)+cos(ang)*cos(ang)1)>0.0001) {cout<<” What?”;}
The abs function, defined in the math library, finds the absolute value of a number. Example:

1. #include <iostream.h>
2. using namespace std;
4. float add (float a, float b) //can accept two float arguments
5. {
6. return a+b;
7. }
8.
9. float input () //can't accept arguments
10. {
11. float a;
12. cout<<” Enter Value:> “;
13. cin>>a;
14. return a;
15. }
16.
17. void show (float num) //can accept one float argument
18. {
19. cout<<” \mResult = “<<num<<endl;
20. }
21.
22. int main ()
23. {
24. float num1, num2, result;
25. num1 = input (); //num1 will be assigned the returned value
26. num2 = input ();
27. result = add (num1, num2);
28. show(result);
29. return 0;
30. }
(Analysis to be done in class)
Since the function call can be used as an expression, lines 27 and 28 may be replaced by a single line
as follows.
27. show (add (num1, num2));

In fact, lines 24 to 28 may be replaced by a single line as follows.


24. show (add (input (), input ()));

Page 43 of 46
Function Scope
A function body, enclosed within a pair of curly braces, forms a new scope. Variables defined within
a function body are not visible outside the function. Such variables are known as local variables.
They exist only while the function is executing. Parameters are also local variables.

Points to Remember
• You should always document what your functions do by writing comments. Common practice
is to write these comments just above the function header.
• You must define a function before all calls to the function. (more on this in Chapter 6)
• Values that are passed into a function are called arguments and the variables that accept these
values are called parameters. The parameters always get a copy of the values (more on this in
Chapter 6)
• When writing a parameter list, each variable must have a data type associated with it. You
can't leave out the data type of a variable even if it has the same type as the variable declared
before it.
• A function call, when used as an expression, evaluates to the value returned by the function.

Example: The following function computes the formula y = mx+ b.


float y (float m, float x, float b)
{ return m*x+b; }

Exercise:
1. Write a function called power what raises a number n to the power r (inputs are of type int and
the result is of type double). Hint:raising a number to the power r is the same as multiplying
the number by itself r times.
2. Write a function that computes the formula ID=ISekVD/TK−1 seen previously. Incorporate
this function into your program.
3. Write a function called is_a_digit that returns true if a character argument passed to it is a
digit ('0' '9') and false otherwise.
4. Write a menu driven program that does addition, subtraction, multiplication, division,
exponentiation, and logarithm of two numbers. Define each operation in its own function. The
program should end only when the user asks it to.

Page 44 of 46
Sample Exam Questions

1. It is often required to find out what day of the week (Monday to Sunday) a given date falls
on. For example, May 15, 2009 falls on a Friday. The following algorithm describes a
procedure for calculating the day of the week given the month, day, and year as integers (M
= 1 for January). Algorithm to calculate the day of the week
i. If the month is January or February, add 12 to M and subtract 1 from Y.
ii. Calculate C as D + 2*M + 3*(M+1)/5 + Y + Y/4 Y/100 + Y/400.
iii. Calculate A as the remainder of dividing C by 7.

iv. If A is 0, then print Monday; if A is 1, then print Tuesday and so on.

a) Write a C++ function that accepts M, D and Y as input and displays the day of the week.
b) Modify the above function to return true if the inputs are valid and false otherwise. (M is
valid if it is between 1 and 12, D is valid depending on the month, Y is valid between
1800 and 2100)
c) Draw the flowchart for the algorithm. The conditions joined by an OR in step i. have to be
shown separately.

2. The following code was placed inside the body of main in a test program. What will be
displayed after the program is compiled and executed?
int a=0, b=1, c=2, d=3; cout<<” Testing...\tStart\n”; while (b<10)
{
cout<<ab*b+c/d<<endl;
d++;
b+=d;
c*=2; }
cout<<” Finished\n”;

3. Some of the following pieces of code compile but give undesired results. For each code,
identify the problem (if any), state its behavior, and correct it.
a) c)
//sum the numbers from 13 to 128 int sum=0; //function to cube a number float cube(float
for (int i=13; i<=128; i++); sum+=i; number)
{
return number*number*number; }
b)
d) //check if a year is a leap year int year;
cout<<” Enter the year: “; if (year /* display a number entered by the user */
%4==0) float num; cout<<” Enter number: “;
1 { cout<<”Leap year\n”; } else cin>>num;
cout<<”Not a leap year\n”; cin>>year; cout<<”Number is: “<<”num”<<endl;
4. Each of the following programs has one or two problems that would not allow it to compile. Find
these problems and correct them. Print the outputs.
a) c)

1. #include <iostream.h> 1. #include <iostream.h>


2. int Main() 2.
3. { 3. void F(int param1, param2)
4. int i=15; 4. {
5. while (i<14) 5. float var1 = 3.2F;
6. cout<<”i is “<<i++<<endl; 6. cout<<param1*param2/var1;
7. return 0; 7. }
8. } 8.
9. int main()
1. #include <iostream.h> 10. {
2. int main() 11. cout<<”initial value: “
3. { 12. <<var1<<endl;
4. float inp; 13. F(3, 2);
5. cout<<”Enter a number: “; 14. return 0;
6. cin>>inp; 15. }
7. cout<<”The natural logarithm”
8. <<” of “<<inp<<” is “
9. <<log(inp)<<endl;
10. }

You might also like