COMP 151 Introduction to Algorithms and Programming

129
1 College of Arts and Sciences Department of Mathematical and Physical Sciences Computer Science Section Spring 2011-2012 COMP 151 Introduction to Algorithms and Programming (3 Hours Lectures and 2 Hours lab) Mr.Lohani Adeeb Khan

Transcript of COMP 151 Introduction to Algorithms and Programming

Page 1: COMP 151 Introduction to Algorithms and Programming

1

College of Arts and Sciences

Department of Mathematical and Physical Sciences Computer Science Section

Spring 2011-2012

COMP 151 Introduction to Algorithms and

Programming

(3 Hours Lectures and 2 Hours lab)

Mr.Lohani Adeeb Khan

Page 2: COMP 151 Introduction to Algorithms and Programming

2

CHAPTER 1

INTRODUCTION TO

ALGORITHMS

Page 3: COMP 151 Introduction to Algorithms and Programming

3

Algorithms and Humans Algorithms are not a natural way of stating a problem’s solution, because we do not normally state our plan of action. We tend to execute as we think about the problem. Hence, there are inherent difficulties when writing an algorithm. We normally tailor our plans of action to the particular problem at hand and not to a general problem (i.e. a nearsighted approach to problem solving). We usually do not write out our plan, because we are usually unaware of the basic ideas we use to formulate the plan. We hardly think about it – we just do it. Computer programmers need to adopt a scientific approach to problem solving, i.e. writing algorithms that are comprehensive and precise. We need to be aware of the assumptions we make and of the initial conditions. Be careful not to overlook a step in the procedure just because it seems obvious. Remember, machines do not have judgment, intuition or common sense! Problem: In a place 4095 bananas were there. First a Monkey came and it ate a single banana, second monkey ate twice of the first monkey, and third monkey ate twice of the second monkey….its going on. At a particular stage all the bananas were exactly (no fraction) eaten by some number of monkeys. How many monkeys came there? Problem: The number 45 is broken into four parts such as part1=X + 2, part2=X – 2, part3=X * 2, and part4=X / 2. In all the parts X is same. Find the value of X.

Page 4: COMP 151 Introduction to Algorithms and Programming

4

What is an Algorithm?

An Algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for obtaining a required output for any legitimate input in a finite amount of time

Is any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output.

More precisely, an algorithm is a method or process to solve a problem satisfying the following properties:

Finiteness – terminates after a finite number of steps

Definiteness – Each step must be carefully and clearly

specified. Input

– Valid inputs must be clearly specified. Output

– Can be proved to produce the correct output given a valid can be proved to produce the correct output given a valid input.

Effectiveness – Steps must be sufficiently simple and basic.

“Computer”

Problem

Algorithm

Input Output

Page 5: COMP 151 Introduction to Algorithms and Programming

5

Basic (primitive) operations involved • Read the input from user • Carry out basic arithmetical computations • Print the output to the user

Variables A variable is a symbolic name assigned to a data item by the programmer. At any particular time, a variable will stand for one particular data, called the value of a variable, which may change from time to time during a computing process. The value of a variable may change many times during the execution of a program. A variable is usually given a name by the programmer. A named location that stores a value

A = 5 B = 3 A C = A + B B = 4 C = A + B A = 7 B A = A + 3 A = A + C C

Arithmetic operators

+ add - subtract * multiply / divide = assign % mod

Page 6: COMP 151 Introduction to Algorithms and Programming

6

Relational operators = = Equal to > Greater than < Less than >= Greater than or equal <= Less than or equal != Not equal to Logical operators

&& AND || OR ! NOT

Examples: IF (x = = 32) && (y = = 7) THEN sum = x + y IF (letter = = 'A') || (letter = = 'E') THEN DISPLAY 'Vowel‘ IF (letter != 'A') THEN DISPLAY 'Not letter A' The key features of an algorithm

• Sequence (also known as Process) • Decision (also known as Selection) • Repetition (also known as Iteration or Looping)

Sequence (Process): Instructions are written one by one Example: Write an algorithm to add two numbers

Start Step 1: Get number1 Step 2: Get number2 Step 3: Sum=number1 + numbert2 Step 4: Display/Print sum Stop

Page 7: COMP 151 Introduction to Algorithms and Programming

7

Decision (Selection): Instructions are written based on some conditions. If the particular condition or conditions are satisfied then the program flow is in one route. Otherwise it follows another route. ie, based on conditions the selection of program flow is jumped into some ways. Conditionals Statement implemented if condition is true A=1, B=2, C=3, D=4 if A < B C = 5 A if A > B D = 4 B if C < D B = B + 1 C Else B = B - 1 D Example: Write and algorithm to compare two numbers and print the smallest number

Start: Step 1: Get number1 Step 2: Get number2 Step 3: If number1< number2 Step 4: print number1 is smaller Step 5: else print number2 is smaller. Stop

1

2

3

4

Page 8: COMP 151 Introduction to Algorithms and Programming

8

Repetition (Looping): In some of the program the same steps are repeated for number of times. In that case the looping structure helps us to do the work. Basically we will study about While loop, Do...While loop and For loop structure. Based on some condition or conditions the iteration is worked out. Example: Computing the Greatest Common Divisor of Two Integers Problem definition:

Greatest Common Divisor (GCD) of two non-negative, not-both-zero integers m and n, denoted by gcd(m, n), is defined as the largest integer that divides both m and n evenly, i.e. with remainder of zero Euclid’s algorithm: gcd(m, n) = gcd(n, m mod n) Eg. gcd(60,24) = gcd(24,12) = gcd(12, 0) = 12

Start Step 1: If n = 0, return the value of m as the answer and

go to Stop; otherwise, proceed to Step 2. Step 2: Divide m by n and assign the value of the

remainder to r. Step 3: Assign the value of n to m and the value of r to n.

Go to Step 1. Stop

Methods of Specifying an Algorithm

• There are two commonly used tools to help to document program logic (the algorithm).

These are 1. Pseudocode. 2. Flowchart.

• We will use both methods here. Generally, flowcharts work well for small problems but Pseudo code is used for larger problems.

Page 9: COMP 151 Introduction to Algorithms and Programming
Page 10: COMP 151 Introduction to Algorithms and Programming
Page 11: COMP 151 Introduction to Algorithms and Programming

9

Pseudocode • Pseudocode is a more simplified version of an

algorithm. • A mixture of a natural language and programming

language • Allows the designer to focus on the logic of the

algorithm without being distracted by details of language syntax.

How to write Pseudocode An algorithm can be written in pseudocode using six (6) basic computer operations:

1. A computer can receive information. Typical pseudocode instructions to receive information are:

Read name Get name Read number1, number2

2. A computer can output (print) information. Typical pseudocode instructions are: Print name

Display Number Write "The average is", avg

3. A computer can perform arithmetic operation Typical pseudocode instructions:

Add number to total, or Total = Total + Number Avg = sum/total

4. A computer can assign a value to a piece of data Typical pseudocode e.g. to assign/give data an initial value:

Initialize total to zero Set count to 0 To assign a computed value: Total = Price + Tax

Page 12: COMP 151 Introduction to Algorithms and Programming

10

5. Computer can compare two (2) pieces of information and select one of two actions.

Typical pseudocode e.g. IF number < 0 then add 1 to neg_number ELSE add one to positive number End-if

6. A computer can repeat a group of actions. Typical pseudocode e.g.

REPEAT until total = 50 read number write number add 1 to total

End-repeat (OR) WHILE total < = 50 do:

read number write number add 1 to total

End-while Example Problem: Read the ‘N’ Number of values and find the Average of these values Pseudocode Header: Algorithm Average Description: This algorithm reads a list of numbers and computes their average. Let: SUM be the total of the numbers read COUNTER to count the number of items in the list AVG be the average of all the numbers Number be the value of element N be the number of elements

Page 13: COMP 151 Introduction to Algorithms and Programming

11

Body: Start Step 1: Set SUM to 0, Set COUNTER to 0. (i.e. initialize variables) Step 2: Read N Step 3: While N > 0 do Step 4: Read Number Step 5: Print Number Step 6: COUNTER=COUNTER + 1 (i.e. increment the COUNTER by 1) Step 7: SUM = SUM + Number (i.e. add number to SUM, storing result in SUM) Step 8: N=N-1 end-while Step 9: if COUNTER = = 0 then Step 10: AVG = 0 else Step 11: AVG = SUM / COUNTER end-if Step 12: Print the SUM Step 13: Print the AVG Stop. Problem: Design a program which accepts as input two numbers and calculates sum and difference and then displays both the sum and the difference. Pseudocode: Body Start Step1: Read Number1 Step2: Read Number2 Step3: Sum = Number1 + Number2 Step4: Difference = Number1 - Number2 Step5: DISPLAY Sum Step6: DISPLAY Difference Stop

Page 14: COMP 151 Introduction to Algorithms and Programming

12

Flowchart: A method of expressing an algorithm by a collection of connected geometric shapes containing descriptions of the algorithm’s steps

Page 15: COMP 151 Introduction to Algorithms and Programming

13

Example: A flowchart that reads the name of 30 students in the class and displays it

Display the name of the student

If number of students<=30

Yes

No

Start

Stop

Read the name of the student

Increase the number of students by 1

Set number of students=1

Page 16: COMP 151 Introduction to Algorithms and Programming

14

Pseudocode: Start Step 1: Set the number of students=1 Step 2: Repeat until number of students<=30 Step 3: Read the Name of the student Step 4: Display the Name of the student Step 5: Increase the number of students by 1 Step 6: End Repeat Stop Example: GCD of two Numbers Pseudocode Start Step 1: Read m, n Step 2: Repeat until n!=0 Step 3: r=m%n Step 4: m=n Step 5: n=r Step 6: End Repeat Step 7: Display ‘m’ as the GCD Stop Problem: Draw the Flowchart for the above Pseudocode. Problem: Draw a flow chart that accepts two numbers and displays the sum Problem: Draw a flowchart for the problem that is accepting two numbers and calculating sum and difference and then displaying the result Example: Draw a flowchart to add all the numbers from 1 to 20.

Page 17: COMP 151 Introduction to Algorithms and Programming

15

Pseudocode:

Start Step 1: Set Number=1 Step 2: Set Sum=0 Step 3: Repeat until Number<=20 Step 4: Sum=Sum + Number Step 5: Number= Number + 1 Step 6: End Repeat Step 7: Display Sum Stop

Display Sum

Number =1

If Number<=20

Sum=Sum+Number

Sum =0

Number =Number+1

Yes

No

Stop

Start

Page 18: COMP 151 Introduction to Algorithms and Programming

16

Example: Flow chart for Average of 3 Numbers

Example: A program has to be written to display the grades of the students in a class of 30 students. Grade is calculated on the basis of percentage (%) marks obtained by the student.

• More than or equal to 80% A • More than or equal to 60% B • More than or equal to 50% C • More than or equal to 40% D • Less than 40% F (Fail) • Draw a flowchart and write the corresponding algorithm

Page 19: COMP 151 Introduction to Algorithms and Programming

17

Mark>=80?

Read the mark of the Student

Mark>=60?

Mark>=50?

Mark>=40?

If Number of Students<=30

Display Grade A

Display Grade D

Display Grade B

Display Grade C

Display Grade F

Yes

Yes

Yes

Yes No

No

No

No

Yes

No

Stop

Start

Increase the Number of Students by one

Set Number of students=1

Page 20: COMP 151 Introduction to Algorithms and Programming

18

Pseudocode: Start Step 1: Set Number of Students=1 Step 2: Repeat Until Number of Students<=30 Step 3: Get the Mark of the student Step 4: Check Mark >= 80 Step 5: If yes Display Grade is ‘A’ then go to Step 13 Step 6: Otherwise Check Mark >= 60 Step 7: If yes Display Grade is ‘B’ then go to Step 13 Step 8: Otherwise Check Mark >= 50 Step 9: If yes Display Grade is ‘C’ then go to Step 13 Step 10: Otherwise Check Mark >= 40 Step 11: If yes Display Grade is ‘D’ then go to Step 13 Step 12: Otherwise Display Grade ‘F’ Step 13: Increase the Number of Students by one Step 14: End Repeat Stop

Page 21: COMP 151 Introduction to Algorithms and Programming

19

Example: Draw a flowchart that accepts 3 numbers say x, y, and z from the user and finds the largest number.

If x > y

Display z is largest

If y > z

If x > z Display x is largest

Display y is largest

Get x, y, z

No No

Yes Yes

Yes

No

Stop

Start

Page 22: COMP 151 Introduction to Algorithms and Programming

20

Pseudocode: Start Step 1: Read the values x, y and z Step 2: Check x > y Step 3: If yes, Check x > z

Step 3.1: If yes, Display ‘x’ is largest then go to Stop Step 3.2: Otherwise Display ‘z’ is largest then go to Stop

Step 4: Otherwise Check y > z Step 4.1: If yes Display ‘y’ is largest then go to Stop Step 4.2: Otherwise Display ‘z’ largest then go to Stop

Stop General Rules for flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines).

2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all flowchart symbols is on the bottom except for the Decision symbol.

3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.

4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does not exceed 3 symbols.

5. Connectors are used to connect breaks in the flowchart. Examples are:

• From one page to another page. • From the bottom of the page to the top of the

same page. 6. Subroutines (Functions) and Interrupt programs have

their own and independent flowcharts. 7. All flow charts start with a Terminal symbol. However,

Subroutines or Functions or interrupt programs start with Predefined Process symbol.

8. All flowcharts end with a terminal.

Page 23: COMP 151 Introduction to Algorithms and Programming

21

Exercises: 1. Draw the flowchart and write the algorithm to find the

given number is odd or even - 3 Marks 2. Draw the flowchart and write the algorithm to find the

square of the given number - 3 Marks 3. Draw the flowchart and write the algorithm to calculate

the area of the circle - 3 Marks 4. Draw the flowchart and write the algorithm to swap the

two numbers - 3 Marks 5. Draw the flowchart and write the algorithm to print the

Fibonacci Series 0,1,1,2,3,5,8,13,21 - 3 Marks 6. An electricity board charges the following rates to

domestic users to discourage large consumption of energy: - 3 Marks

For the first 100 units – 10 Paisa per unit For next 200 units – 20 Paisa per unit Beyond 300 units – 30 Paisa per unit

If the total cost is more than 10 OMR then an additional surcharge of 15% is added. Draw the flowchart and write the algorithm to calculate the amount for number of units consumed.

7. Draw the flowchart and write the algorithm to read 100 different numbers and then display the sum of numbers.

- 3 Marks 8. Draw the flowchart and write the algorithm to read two

numbers and then display the largest - 3 Marks 9. Draw the flowchart and write the algorithm to read two

numbers and then display the smallest - 3 Marks 10. Draw the flowchart and write the algorithm to read three

numbers and then display the smallest - 3 Marks

Page 24: COMP 151 Introduction to Algorithms and Programming

CHAPTER – 2

INTRODUCTION TO C++ PROGRAMMING

1

Page 25: COMP 151 Introduction to Algorithms and Programming

Introduction to C++ Programming Bjarne Stroustrup of AT&T Bell Laboratories

developed C++ in the early 1980s. Stroustrup designed C++ to be a better C. Most of C is a subset of C++, and so most C programs are also C++ programs. (The reverse is not true; many C++ programs are definitely not C programs.) Unlike C, C++ has facilities for classes and so can be used for object-oriented programming. C++ Program structure : Example C++ Program // My first program in C++ /*To Explain the C++ program structure This is the Best Example Program*/ #include<iostream> using namespace std; int main( ) { cout<<"This is the First Program \n"; cout<<"University of Nizwa"; return(0); } Output This is the First Program University of Nizwa 1. Comment Lines // my first program in C++ /*To Explain the C++ program structure This is the Best Example Program*/ - Explain programs to other programmers - Improve program readability - Ignored by compiler

– Single-line comment • Begin with // • Example

– // This is a text-printing program. – Multi-line comment

• Start with /* • End with */

2

Page 26: COMP 151 Introduction to Algorithms and Programming

Note: The programmer can also use them to include short explanations or observations within the source code itself. 2. Preprocessor Directive #include<iostream> is a preprocessor directive, which is the message to the C++ preprocessor. Lines that begin with # are processed by the preprocessor before the program is compiled. This line notifies the preprocessor to include in the program the contents of the input/output stream header file<iostream>. This file must be included for any program that outputs data to the screen or inputs data from the keyboard using c++ style stream input/output. 3. using namespace std All the identifiers (variables, functions, classes and objects) in the ANSI standard header files are part of the std namespace. This rule is almost as recent as the ANSI standard itself(1997) and many older compilers do not comply with this rule. In ANSI C++, cin and cout are written as std::cin and std::cout. If you do not wish to specify std:: with cin or cout (or any of the ANSI standard identifiers), you must write the following statement in your program: using namespace std; 4. Function main C++ programs begin executing at function main, even if main is not the first function in the program.

– A part of every C++ program • Exactly one function in a program must be

main – Can “return” a value – Example

• int main() – This main function returns an integer

(whole number) – Body is delimited by braces ({ })

3

Page 27: COMP 151 Introduction to Algorithms and Programming

• Statements – Instruct the program to perform an action – All statements end with a semicolon (;)

• Stream insertion operator << – Example

• cout<<"Hello"; • Inserts the string "Hello" into the

standard output • Displays to the screen

• Escape characters – A character preceded by "\"

• Indicates “special” character output Character Name Purpose

\n New line Position the cursor to the beginning of the next line.

\t Horizontal tab Move screen cursor to the next tab stop

\\ Backslash Used to print backslash character

\’ Single quote Used to print single quote \" Double quote Used to print double quote \? Question mark Used to print question mark

Common Programming Error

• Omitting the semicolon at the end of a C++ statement is a syntax error.

• A syntax error occurs when the compiler encounters code that violates C++’s language rules (i.e., its syntax).

• The compiler normally issues an error message to help the programmer locate and fix the incorrect code.

• You will be unable to execute your program until you correct all the syntax errors in it.

4

Page 28: COMP 151 Introduction to Algorithms and Programming

Good Programming Practice Many programmers make the last character printed

by a function a new line (\n). This ensures that the function will leave the screen cursor positioned at the beginning of a new line. Identifiers

The names for variables, functions and constants are called identifiers Variables

– Location in memory where value can be stored – Common data types (fundamental, primitive or

built-in) • int – integer numbers • char – characters • float, double – floating point numbers

– Declare variables with name and data type before use

• int integer1; • int integer2; • int sum;

– Can declare several variables of same type in one declaration

• Comma-separated list • int integer1, integer2, sum;

Rules for Variable names • Valid identifier • Series of characters (letters, digits, underscores) • Cannot begin with digit • Case sensitive (ie Both Small letters and Capital

letters allowed. But both are not same variable. Example: int age,Age,AGE; Here variable age, Age and AGE are not same. All are different variable. • Can not have same name as reserved keywords. But

the Keywords in Capital Letters are allowed.

5

Page 29: COMP 151 Introduction to Algorithms and Programming

The standard reserved keywords are: struct int double auto

switch long else break typedef register enum case union return extern char unsigned short float const void signed for continue volatile sizeof goto default while static if do

Very important:

The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers. Note:

C++ allows identifiers of any length, but your C++ implementation may impose some restrictions on the length of identifiers. Use identifiers of 31 characters or fewer. Good Programming Practice

Choosing meaningful identifiers helps make a program self-documenting—i.e a person can understand the program simply by reading it rather than having to refer to manuals or comments.

Avoid identifiers that begin with underscores and double underscores, because C++ compilers may use names like that for their own purposes internally.

6

Page 30: COMP 151 Introduction to Algorithms and Programming

Example C++ Program: Adding Integers // program to add two integer numbers #include<iostream> using namespace std; int main( ) { int number1,number2,sum; cout<<"Enter number1 \n"; cin>>number1; cout<<" Enter number2 \n"; cin>>number2; sum=number1+number2; cout<<"Sum is :"<<sum<<endl; return(0); } Output Enter number1 12 Enter number2 5 Sum is:17 Program Explanation

• Input stream object – cin from <iostream.h>

• Usually connected to keyboard • Stream extraction operator >>

– Waits for user to input value, press Enter key

– Stores value in variable to right of operator

– Converts value to variable data type • Example

– cin>>number1; • Reads an integer typed at the

keyboard • Stores the integer in variable

number1

7

Page 31: COMP 151 Introduction to Algorithms and Programming

• Assignment operator = – Assigns value on left to variable on right – Binary operator (two operands) – Example:

• sum=number1+number2; – Add the values of number1 and

number2 – Store result in sum

• Stream manipulator endl – Outputs a newline

• Concatenating stream insertion operations – Use multiple stream insertion operators in a

single statement – Stream insertion operation knows how to output

each type of data – Also called chaining or cascading – Example

• cout<<"Sum is :"<<sum<<endl; – Outputs "Sum is:" – Then, outputs sum of number1 and

number2 which is written in sum – Then, outputs newline

• Variable names – Correspond to actual locations in computer's

memory – Every variable has name, type, size and value – When new value placed into variable, overwrites

old value – Example

• sum=number1+number2; – Value of sum is overwritten

8

Page 32: COMP 151 Introduction to Algorithms and Programming

Common (or) fundamental (or) primitive (or) built-in Data types

Type Size Range of Values

Char 1 byte signed: -128 to 127

unsigned: 0 to 255

short int 2 bytes signed: -32768 to 32767 unsigned: 0 to 65535

int 4 bytes signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

long int 4 bytes signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

bool 1 byte true or false

float 4 bytes 3.4x10-38 to 3.4x1038

double 8 bytes 1.7x10-308 to 1.7x10308

long double 8 bytes 1.7x10-308 to 1.7x10308

Note: Some compilers use 10 bytes for long double. This allows a range of 3.4x10-4932 to 1.1x104932

Declaration of variables

In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier. For example:

int a; float number1;

These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the

9

Page 33: COMP 151 Introduction to Algorithms and Programming

identifier number1. Once declared, the variables a and number1 can be used within the rest of their scope in the program.

If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas. For example: int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as: int a; int b; int c;

The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero). This can be specified by using either the specifier signed or the specifier unsigned before the type name. For example: unsigned short int age; signed int balance;

By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written: int balance; with exactly the same meaning (with or without the keyword signed)

10

Page 34: COMP 151 Introduction to Algorithms and Programming

Example Program //operating with variables #include<iostream> using namespace 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); } Output 4 Scope of Variables: All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int. A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.

11

Page 35: COMP 151 Introduction to Algorithms and Programming

#include<iostream> using namespace std; int a; char name[50]; Global variables unsigned int numberofsons; int main() { unsigned int age; Local Variables float average,percentage; cout<<”Enter your age:”; cin>>age; Instructions … } Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa. Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized: type identifier=initial_value;

12

Page 36: COMP 151 Introduction to Algorithms and Programming

For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write: int a=0;

The other way to initialize variables, known as

constructor initialization, is done by enclosing the initial value between parentheses (): type identifier(initial_value) ; For example: int a(0); Both ways of initializing variables are valid and equivalent in C++. Example Program //initialization of variables #include<iostream> using namespace std; int main() { int a=5; //initial value=5 int b(2); //initial value = 2 int result; //initial value undetermined a=a+3; result=a-b; cout<<result; return(0); } Output 6

13

Page 37: COMP 151 Introduction to Algorithms and Programming

Constants Constants are expressions with a fixed value.

There are 3 types of Constants 1. Literals 2. Defined Constant 3. Declared Constant

1. Literals Literals are used to express particular values within

the source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote: a=5; the 5 in this piece of code was a literal constant.

Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. Integer Numerals 1776 707 -273

They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character. There is no doubt that it is a constant: whenever we write 1776 in a program, we will be referring to the value 1776.

In addition to decimal numbers (those that all of us are used to use every day) C++ allows the use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to precede it with a 0 (zero character). And in order to express a hexadecimal number we have to precede it with the characters 0x (zero,x). For example,

14

Page 38: COMP 151 Introduction to Algorithms and Programming

the following literal constants are all equivalent to each other: 75 // decimal 0113 // octal 0x4b // hexadecimal

All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively. Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of type int. However, we can force them to either be unsigned by appending the u character to it, or long by appending l: 75 // int 75u // unsigned int 75l // long 75ul // unsigned long Note: In both cases, the suffix can be specified using either upper or lowercase letters. Example Program #include<iostream> using namespace std; int main() { int a; long b; unsigned long c; short int d; a=45; b=189000; c=4294967295; d=12; cout<<"Memory size of integer is"<<sizeof(a)<<endl; cout<<"Value of a is"<<a<<endl; cout<<"Memory size of long integer is"<<sizeof(b)<<endl; cout<<"Value of b is"<<b<<endl; cout<<"Memory size of unsigned long integer is"<<sizeof(c)<<endl;

15

Page 39: COMP 151 Introduction to Algorithms and Programming

cout<<"Value of c is"<<c<<endl; cout<<"Memory size of short integer is"<<sizeof(d)<<endl; cout<<"Value of d is"<<d<<endl; return(0); } Output Memory size of integer is4 Value of a is45 Memory size of long integer is4 Value of b is189000 Memory size of unsigned long integer is4 Value of c is4294967295 Memory size of short integer is2 Value of d is12 Character and string literals There also exist non-numerical constants, like: 'z' 'p' "Hello world" "How do you do?"

The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes ("). Note: When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: x 'x' x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.

16

Page 40: COMP 151 Introduction to Algorithms and Programming

Example Program #include<iostream> using namespace std; int main() { char letter; letter='A'; cout<<letter<<endl; letter='B'; cout<<letter<<endl; cout<<"The size of char is"<<sizeof(letter)<<endl; return(0); } Output A B The size of char is1 Relation between Character and Integer Data type

We can use integer data type to store characters, because characters are internally represented by numbers. Each printable and nonprintable characters, is assigned a unique number. The most commonly used method for encoding characters is ASCII, which stands for American Standard Code for Information Interchange.

When a character is stored in memory, it is actually the numeric code that is stored. When the computer is instructed to print the value on the screen, it displays the character that corresponds with the numeric code.

Notice that the number 65 is the code for ‘A’, 66 is the code for ‘B’ and so on. For small letter ‘a’ the code is 97, and for ‘b’ 98 and so on. For the character ‘0’(zero when it is the character type) the code is 48, for the character ‘1’(one when it is character type) the code is 49 and so on.

17

Page 41: COMP 151 Introduction to Algorithms and Programming

Example Program #include<iostream> using namespace std; int main() { char letter; int n; letter=48; cout<<letter<<endl; letter=97; cout<<letter<<endl; n='9'; cout<<n<<endl; n='Z'; cout<<n<<endl; return(0); } Output 0 a 57 90 Floating Point Numbers

Floating point numbers are stored in a manner similar

to scientific notation. Take the number 47,281.97. In scientific notation this number is 4.728197 x 104. (104 is equal to 10,000, and 4.728197 x 10,000 is 47,281.97). The first part of the number 4.728197 is called the mantissa. The mantissa is multiplied by a power of ten. Computers typically use E notation to represent floating point values. In E notation, the number 47,281.97 would be 4.728197E4. The part of the number before the E is the mantissa, and the part after the E is the power of 10. When the floating point number is stored in memory, it is stored as the mantissa and the power of 10.

18

Page 42: COMP 151 Introduction to Algorithms and Programming

Decimal Notation Scientific Notation E notation 247.91 2.4791 x 102 2.4791E2 0.00072 7.2 x 10-4 7.2E-4 2,900,000 2.9 x 106 2.9E6

In C++ there are three data types that can represent floating point numbers. They are

float double long double The float type is considered single precision. The

double data type is usually twice as big as float, so it is considered double precision. As you have probably guessed, the long double is intended to be larger than the double. The default type for floating point literals is double. If you explicitly want to express a float or long double numerical literal, you can use the f or l suffixes respectively: 3.14159L // long double 6.02e23f // float Example Program #include<iostream> using namespace std; int main() { float distance; double mass; distance=1.495979E11f; mass=1.989E30; cout<<"The Sun is"<<distance<<"meters away \n"; cout<<"The Sun's mass is"<<mass<<"kilograms \n"; cout<<"The size of float is"<<sizeof(distance)<<endl; cout<<"The size of double is"<<sizeof(mass)<<endl; cout<<"The size of long double is"<<sizeof(long double)<<endl; return(0); } Output The Sun is 1.49598e+011meters away

19

Page 43: COMP 151 Introduction to Algorithms and Programming

The Sun’s mass is 1.989e+030 kilograms The size of float is4 The size of double is8 The size of long double is8 Note: in the source code the literals were written as 1.495979E11 and 1.989E30, but the program printed them as 1.49598e+011 and 1.989e+030. The two sets of numbers are equivalent. (The plus sign in front of the exponent is also optional). Note: Any of the letters than can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings. Boolean literals

There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by using the Boolean literals true and false. The bool data type allows you to create small integer variable that are suitable to holding true or false values. Example Program #include<iostream> using namespace std; int main() { bool va; va=true; cout<<va<<endl; va=false; cout<<va<<endl; return(0); } Output 1 0 As you can see from the program output, the value true is represented in memory by the number 1, and the false is represented by 0.

20

Page 44: COMP 151 Introduction to Algorithms and Programming

2. Defined constants (#define) You can define your own names for constants that

you use very often without having to resort to memory consuming variables, simply by using the #define preprocessor directive. Its format is: #define identifier value For example: #define PI 3.14159265 #define NEWLINE '\n'

This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example: Example Program //defined constants: calculate circumference #include<iostream> using namespace std; #define PI 3.14159 #define NEWLINE '\n' int main() { double r=3.5; double circle; circle=2*PI*r; cout<<circle; cout<<NEWLINE; return(0); } Output: 21.9911

In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to

21

Page 45: COMP 151 Introduction to Algorithms and Programming

which they have been defined (3.14159265 and'\n' respectively).

Note: The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces. 3. Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: const int pathwidth = 100; const char tabulator = '\t';

Here, pathwidth and tabulator are two typed

constants. They are treated just like regular variables except that their values cannot be modified after their definition. Any attempt to alter the value of a variable defined with const will give an error from the compiler. Manipulators:

Manipulators are operators used with the insertion operator << to modify or manipulate the way of data display. 1. The endl Manipulator:

This is a manipulator that causes a linefeed to be inserted into the stream. It has the same effect as sending the single ‘\n’ character. 2. The setw(n) Manipulator:

You may think of each value displayed by cout as occupying a field: an imaginary box with a certain width. The default field is just wide enough to hold the value. That is, the integer 567 will occupy a field three characters

22

Page 46: COMP 151 Introduction to Algorithms and Programming

wide, and the string “pajamas” will occupy a field seven characters wide. However, in certain situations this may not lead to optimal results. Here’s an example. The width1 program prints the names of three cities in one column, and their populations in another. Example Program 1 //width1.cpp //demonstrates need for setw manipulator #include<iostream> using namespace std; int main() { long int pop1=2425785,pop2=47,pop3=9761; cout<<”LOCATION ”<<”POPULATION”<<endl; cout<<”Portcity ”<<pop1<<endl; cout<<”Hightown ”<<pop2<<endl; cout<<”Lowville ”<<pop3<<endl; return(0); } Output L O C A T I O N P O P U L A T I O N P o r t c i t y 2 4 2 5 7 8 5 H i g h t o w n 4 7 L o w v i l l e 9 7 6 1

Unfortunately, the output of this program is not ideal. It’s hard to compare the numbers. It would be better if they lined up to the right. Also, we had to insert spaces into the names of the cities to separate them from numbers. This is an inconvenience.

Here’s a variation of this program, width2, that uses setw manipulator to eliminate these problems by specifying field widths for the names and numbers:

23

Page 47: COMP 151 Introduction to Algorithms and Programming

Example Program 2 //width2.cpp //demonstrate the setw manipulator #include<iostream> #include<iomanip> using namespace std; int main() { long int pop1=2425785,pop2=47,pop3=9761; cout<<setw(8)<<”LOCATION”<<setw(12)<<”POPULATION”<<endl; cout<<setw(8)<<”Portcity”<<setw(12)<<pop1<<endl; cout<<setw(8)<<”Hightown”<<setw(12)<<pop2<<endl; cout<<setw(8)<<”Lowville”<<setw(12)<<pop3<<endl; return(0); } Output L O C A T I O N P O P U L A T I O N P o r t c i t y 2 4 2 5 7 8 5 H i g h t o w n 4 7 L o w v i l l e 9 7 6 1

The setw manipulator causes the number or string that follows it in the stream to be printed within a field n characters wide, where n is the argument to setw(n). The value is right-justified within the field. If we want to display the output in left justified manner we can do the same with setw() manipulator. The keyword left should be given after setw(n). Once the default (right justified) is changed with left alignment then all the setw(n) follows the left alignment. Again if you want to change the right then you have to give the right keyword after the corresponding setw(n).Since this is the default, it is only used to override the effects of left. Only useful after setw(n).

24

Page 48: COMP 151 Introduction to Algorithms and Programming

Example Program #include<iostream> #include<iomanip> using namespace std; int main() { cout<<setw(10)<<left<<"Hello"<<setw(10)<<"Hello"<<endl//1st hello and 2nd hello both aligned in left manner cout<<setw(10)<<left<<"Hello"<<setw(10)<<right<<"Hello"<<endl; //1st hello is left aligned and 2nd hello right aligned return(0); } Output H e l l o H e l l o H e l l o H e l l o 3. setprecision(n) Manipulator This manipulator 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. Example program #include<iostream> #include<iomanip> using namespace std; int main() { double b=0.234009; cout<<setprecision(2)<<b<<endl; return(0); } Output 0.23 Note: When you use these manipulators you must insert #include<iomanip> header file in your program.

25

Page 49: COMP 151 Introduction to Algorithms and Programming

Exercises: 1. A function name must be followed by____ - 1 Mark 2. A function body is delimited by_________ - 1 Mark 3. Why is the main() function special? - 1 Mark 4. Specify how many bytes are occupied by the following

data types in Microsoft C/C++ - 2 Marks a).Type int b).Type long double c).Type float b).Type long int

5. True or False: A variable of type char can hold the value 301 - 1 Mark

6. What kind of program elements are the following? a).12 - 2 Marks b).’a’ c).4.28915 d).JungleJim e).JungleJim()

7. Write statements that display on the screen - 3 Marks a).The character ‘x’ b).The name Jim c).The number 509

8. What header file must you #include with your source file to use cout and cin? - 1 Mark

9. Write a statement that gets a numerical value from the keyboard and places it in the variable temp. - 1 Mark

10. What header file must you #include with your program to use setw? - 1 Mark 11. True or False: 1. Local variables can be accessed anywhere in the program. 2.constant variable values can be modified in the program - 2 Marks 12. Write a program that generates the following table:

1990 135 - 2 Marks 1991 7290 1992 11300

1993 16200 1994 1123467

26

Page 50: COMP 151 Introduction to Algorithms and Programming

13. Write a program to display the following - 2 Marks # ## ### #### 14. Write a program to display the following - 2 Marks 1 1 2 1 2 3 1 2 3 4 15. Which of the following is(are) proper identifier(s)? Give

the reason also - 3 Marks a).3digit b)._name c).State d).signed e).ABC f).REGISTER g).Form23 h).Distance_to_calculate i).hEllO 16. Write a program to display the following - 2 Marks ???? ??? ?? ? 17. Identify the following literals - 3 Marks a).123.45 b).5.64567L c).90L d).45u e).79uL f).1.23e12f g).-456 h).0xAA i).062 j).”hai”

27

Page 51: COMP 151 Introduction to Algorithms and Programming

CHAPTER - 3

OPERATORS IN C++

1

Page 52: COMP 151 Introduction to Algorithms and Programming

Operators Once we know of the existence of variables and

constants, we can begin to operate with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning. Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the C++ language are: + Addition - Subtraction * Multiplication / Division % Modulo

Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if we write: a = 11 % 3; the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3. Common Programming Error Attempting to use the modulus operator (%) with non-integer operands is a compilation error

2

Page 53: COMP 151 Introduction to Algorithms and Programming

Assignment Operators The assignment operator assigns a value to a variable. a = 5;

This statement assigns the integer value 5 to the variable a. The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of an operation or any combination of these.

The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never the other way: a=b; This statement assigns the value of b to a. So the value of a is overwritten by the value of b.

Example program //assignment operator #include<iostream> using namespace std; int main() { int a,b; a=10; b=4; a=b; b=7; cout<<"a="<<a<<endl; cout<<"b="<<b; return(0); } Output a=4 b=7

3

Page 54: COMP 151 Introduction to Algorithms and Programming

This code will give us as result that the value contained in a is 4 and the one contained in b is 7. Notice how a was not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-to left rule). Compound assignment (or) Arithmetic assignment operators (+=, -=, *=, /=, %=): d-=4 means (d = d - 4) e*=5 means (e = e * 5) f/=3 means (f = f / 3) g%=9 means (g = g % 9)

Assignment operator

Sample expression

Explanation Assigns

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g

// compound assignment operators Example Program #include<iostream> using namespace std; int main () { int a, b=3; a=b; a+=2; // equivalent to a=a+2 cout<<a; return(0); }

4

Page 55: COMP 151 Introduction to Algorithms and Programming

Output 5 Increment and Decrement Operators

• Increment operator ++ – Increments variable by one

• Example c++ means c=c+1 or c+=1;

• Decrement operator -- – Decrement variable by one

• Example c--means c=c-1 or c-=1;

• Pre-increment

– When the operator is used before the variable (++c) Value of the variable c is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression

• Post-increment – When the operator is used after the variable (c++)

Value stored in variable c is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression.

Operator Called Sample expression Explanation

++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

5

Page 56: COMP 151 Introduction to Algorithms and Programming

Example 1 B=3; A=++B; // A contains 4, B contains 4 Example 2 B=3; A=B++; // A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased. Good Programming Practice

Unlike binary operators, the unary increment and decrement operators should be placed next to their operands, with no intervening spaces. Example Program //Pre-incrementing and Post-incrementing.#include<iostream> using namespace std; int main() { int c; // demonstrate post-increment c=5; // assign 5 to ccout<<c<<endl; // print 5 cout<<c++<<endl; // print 5 then post-incrementcout<<c<<endl; // print 6cout<<endl; // skip a line// demonstrate pre-incrementc=5; // assign 5 to ccout<<c<<endl; // print 5cout<<++c<<endl;// pre-increment then print 6cout<<c<<endl; // print 6return(0); }

6

Page 57: COMP 151 Introduction to Algorithms and Programming

Output 5 5 6 5 6 6

Note:

• If c = 5, then – cout<<++c;

• c is changed to 6 • Then prints out 6

– cout<<c++; • Prints out 5 (cout is executed before the

increment) • c then becomes 6

• When variable is not in an expression – Pre-incrementing and Post-incrementing have

same effect • Example

• ++c; cout<<c; and c++; cout<<c; are the same

Relational and equality operators ( ==, !=, >, <, >=, <= )

In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. We may want to compare two expressions, for

7

Page 58: COMP 151 Introduction to Algorithms and Programming

example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++: == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to Here there are some examples: (7==5) // evaluates to false. (5>4) // evaluates to true. (3!=2) // evaluates to true. (6>=6) // evaluates to true. (5<5) // evaluates to false.

Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6 (a==5) // evaluates to false since a is not equal to 5. (a*b>=c) // evaluates to true since (2*3 >= 6) is true. (b+4>a*c) // evaluates to false since (3+4 > 2*6) is false. ((b=2)==a) // evaluates to true. Common Programming Error

• A syntax error will occur if any of the operators ==, !=, >= and <= appears with spaces between its pair of symbols.

• Confusing the equality operator == with the assignment operator = results in logic errors.

• The equality operator should be read “is equal to,” and the assignment operator should be read “gets” or “gets the value of” or “is assigned the value of.”

• Some people prefer to read the equality operator as “double equals.”

8

Page 59: COMP 151 Introduction to Algorithms and Programming

Logical operators ( !, &&, || ) ! Operator The operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and 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. Basically, it returns the opposite Boolean value of evaluating its operand.

For example: !(5 ==5) // evaluates to false because the expression at its right (5 == 5) is true. !(6<= 4) // evaluates to true because (6<=4) would be false. !true // evaluates to false !false // evaluates to true.

&& OPERATOR

The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a&&b:

9

Page 60: COMP 151 Introduction to Algorithms and Programming

|| OPERATOR 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. Here are the possible results of a || b:

For example: ((5==5)&&(3>6)) // evaluates to false (true && false). ((5==5)||(3>6)) // evaluates to true (true || false). Conditional operator ( ? : ) or Ternary Operator

The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: condition ? result1 : result2 If condition is true the expression will return result1, if it is not it will return result2. 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5. 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2. 5>3 ? a : b // returns the value of a, since 5 is greater than 3. a>b ? a : b // returns whichever is greater, a or b.

10

Page 61: COMP 151 Introduction to Algorithms and Programming

Example Program //conditional operator #include<iostream> using namespace std; int main() { int a,b,c; a=2; b=7; c=(a>b)?a:b; cout<<c; return(0); } Output 7

In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7. Explicit type casting operator

Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses ()

int i; float f =3.14; i=(int)f;

The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int).

11

Page 62: COMP 151 Introduction to Algorithms and Programming

Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses: i=int(f); Both ways of type casting are valid in C++. sizeof()

This operator accepts one parameter, which can be either a type or a variable itself and returns(integer) the size in bytes of that type or object: int a; a=sizeof(char);

This will assign the value 1 to a, because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. Precedence of operators

When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: a = 5 + 7 % 2 We may doubt if it really means: a = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a result of 0 The correct answer is the first of the two expressions, with a result of 6.

12

Page 63: COMP 151 Introduction to Algorithms and Programming

Precedence of arithmetic operators – Operators in parentheses evaluated first – Multiplication, division, modulus applied next

• Operators applied from left to right – Addition, subtraction applied last

• Operators applied from left to right

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*

/

%

Multiplication

Division

Modulus

Evaluated second. If there are several, they are evaluated left to right.

+ -

Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example: a=5+7%2; might be written either as: a=5+(7%2); or a=(5+7)%2; depending on the operation that we want to perform.

So if you want to write complicated expressions and you are not completely sure of the precedence levels, always include parentheses. It will also become a code easier to read.

13

Page 64: COMP 151 Introduction to Algorithms and Programming

There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. Associativity: In the above table we mentioned that if there are several operators in the same precedence then it is evaluated from left to right. It is called as Associativity of operator. In c++ the binary operators *,/,%,+,- are all left associative. That is, it is evaluated from left to right when the expression having the same operator. Example: 9-5-1 means (9-5)-1=4-1=3 Good Programming Practice Using redundant parentheses in complex arithmetic expressions can make the expressions clearer. Example

14

Page 65: COMP 151 Introduction to Algorithms and Programming

Exercises 1. The expression 19 % 4 evaluates to ______ - 1 Mark 2. The increment operator increases the value of a

variable by how much? - 1 Mark 3. Assuming var1 starts with the value 20, what will the

following code fragment print out? - 2 Marks cout<<var1--; cout<<++var1;

4. Write a program to generate the following output - 2 Marks 10 20 19 Use an integer variable to set the value 10, an arithmetic assignment operator to generate the 20, and a decrement operator to generate the 19.

5. Write a program to find a given year is leap year or not through conditional operator. - 2 Marks

6. Evaluate the following expressions: - 4 Marks a).z=7*10-5%3*4+9 b).y=(7*(10-5)%3)*4+9 c).t=12-4+15/3%5*2+6*2 d).x=5+3+8*9+6*4

7. Show the order of evaluation and find the final result for each of the following expression. - 3 Marks Assume x=6 y=3 z=2 w=1

1. R= x*(y+z*w-1)%(y+1) 2. R=(x+1)*(y-1)/(w+z%2)

15

Page 66: COMP 151 Introduction to Algorithms and Programming

CHAPTER – 4

CONTROL STRUCTURES

1

Page 67: COMP 151 Introduction to Algorithms and Programming

Control Structures A program is usually not limited to a linear sequence of

instructions. During its process it may deviate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures we are going

to have to introduce a new concept: the compound statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }: {statement1; statement2; statement3;}

Most of the control structures that we will see in this

section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}).But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block. Only three control structures needed Three control structures

• Sequence structure – Programs executed sequentially by

default • Selection structures

– if, if…else, switch • Repetition structures

– while, do…while, for

2

Page 68: COMP 151 Introduction to Algorithms and Programming

Selection Structures (or) Conditional Structures (or) Branching Structures 1. if structure If keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if(condition) statement; where condition is the expression that is being evaluated.

If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure.

Statement

Condition YES

NO

Continue

For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if(x == 100) cout << "x is 100";

3

Page 69: COMP 151 Introduction to Algorithms and Programming

If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }: if(x == 100) { cout<<"x is "; cout<<x; } 2. if …else statement

We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is: if(condition) statement1; else statement2;

Statement1

Condition YES NO

Continue

Statement2

4

Page 70: COMP 151 Introduction to Algorithms and Programming

For example:

100";

<"x is not 100";

rints on the screen x is 100 if indeed x has a value of 100,

ay if …else statements (or) if…else…if ladder

if(x==100) cout<<"x iselse cout< pbut if it has not -and only if not- it prints out x is not 100. 3. Multi-w

we m

(condition-1)

(condition-2)

(condition-3)

(condition-n)

efault statement; statement-x;

When a series of many conditions have to be checkeday use the ladder else if statement which takes the

following general form ifstatement-1;

else ifstatement-2;

else ifstatement-3;

else ifstatement-n;

else d

This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement–x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.

5

Page 71: COMP 151 Introduction to Algorithms and Programming

Condition-1 YES NO

Statement-1

6

Condition-2Statement-2

YES

Default Statement

NO

Condition-3 Statement-3 YES

NO

Statement-n YES Condition-n

NO

Statement-x

Page 72: COMP 151 Introduction to Algorithms and Programming

The if + else structures can be concatenated with the intention of verifying a range of values.

The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):

if(x > 0) cout<<"x is positive"; else

if(x<0) cout<<"x is negative";

else cout<<"x is 0";

Example program using if else ladder to grade the student according to the following rules.

Marks Grade

>=90 A

>=80 B

>=70 C

>=60 D

<60 F

7

Page 73: COMP 151 Introduction to Algorithms and Programming

Example: Algorithm steps If stu

If student’s grade is greater than or equal to 80

int “B”

If student’s grade is greater than or equal to 70 int “C” If student’s grade is greater than or equal to 60 else

“F”

++ Program Steps

dent’s grade is greater than or equal to 90 Print “A” else

Pr else

Pr else

Print “D” Print C if(s rade>= cout<<"A"; else if(studentGrade>= 80) cout<<"B"; el if(studentGrade>=70) cout<<"C"; e if(studentGrade >= 60) cout<<"D"; else cout<<"F";

tudentG 90)

se

lse

8

Page 74: COMP 151 Introduction to Algorithms and Programming

4. Nested if Statements tatements can be nested, i.e. used inside

else corresponds to its closest preceding if ion)

if(e {

}

{

lse statement;

if and if-else sanother if or else statement

Everyif(express{ xpression) statement; else statement; } } e Example: to find the givgreater than oif(first { cout<<"These} else { if(firs { cout<<"The firs } else

en two numbers are equal, or ther

== second)

two numbers are equal.";

t > second)

t number is bigger.";

{ cout<<"The second is bigger."; }

}

9

Page 75: COMP 151 Introduction to Algorithms and Programming

5. The selective structure: switch…case

made from more than two possibilities by using if-else ladder statements. However a less unwieldy method in some cases

h statement.

: h(selector)

label1 : up of statement1 ;

break;

group of statement2 ; break;

group of statementn ;

optional break;

The selector may be an integer or character variable or expression that evaluates to an integer or a character.

s ted and the value compared with each ase labels. The case labels must have the same type

different. Switch lu s selector and checks if it is equivalent to label1, if it t tes group of statements 1 until it finds the break e ent. When it finds this break statement the program

ve structure If the value h selector cannot be matched with any of the case

bels then the statement associated with default is

In the last Lesson it was shown how a choice could be

is to use a switc The general form of a switch…case statement isswitc{ case

gro

case label2 :

. . . case labeln :

break; default :

statementd; //

}

anThe elector is evaluaof the cas the selector and they must all beeva ateis, i execustat mjumps to the end of the switch selectiof t e la

10

Page 76: COMP 151 Introduction to Algorithms and Programming

executed. The default is optional but it should only be left out if it i

losed in curly brackets).

s certain that the selector will always take the value of one of the case labels. Note that the statement associated with a case label can be a single statement or a sequence of statements (without being enc

11

Page 77: COMP 151 Introduction to Algorithms and Programming

For example The following switch statement will set the variable grade to the character A, B or C depending on whether the variable i has the value 1, 2, or 3. If i has none of the values 1, 2, or 3 then a warning message is output. switch(i) { case 1:

grade = 'A'; break;

case 2: grade = 'B'; break;

case 3: grade = 'c'; break;

default: cout<<i<<"not in range"; break;

} The following statement writes out the day of the week

depending on the value of an integer variable day. It assumes that day 1 is Sunday. switch(day) { case 1:

cout<<"Sunday"; break;

case 2: cout<<"Monday"; break;

case 3: cout<<"Tuesday"; break;

12

Page 78: COMP 151 Introduction to Algorithms and Programming

case 4: cout<<"Wednesday"; break;

case 5: cout<<"Thursday"; break;

cout<<"Friday"; k;

caseSaturday";

k; defau

Not an allowable day number"; ak;

}

has already been ensured that day takes a value between 1 and 7 then the default case may be missed out.

It is allowable to associate several case labels with one statement. For example, if we did not include a break

end of the switch selective would continue executing the rest of statements

til it reaches either a break instruction or the end of the lective block. This makes unnecessary to include

braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of

ns for different possible values for the expression being

ple

case 6:

brea 7: cout<<"brealt: cout<<"bre

If it

statement after the first group for case one, the program will not automatically jump to the block and it unswitch se

instructio evaluated.

For exam if the above example is amended to write out whether day is a weekday or is part of the weekend:

13

Page 79: COMP 151 Introduction to Algorithms and Programming

switch(day) { case

ekend day";

casecase

caseThis is a weekday";

k; defau

Not a legal day"; break;

Switc

oth of the following code fragments have the same behavior:

switc

lue of x nknown";

{ cout<<"value of x unknown";

1: case 7:

cout<<"This is a webreak;

case 2: 3: 4:

case 5: 6: cout<<"brealt: cout<<"

} h statement something similar to what we did at the

beginning of this section with if else ladder. B

h example switch (x) { case 1: cout<<"x is 1"; break; case 2: cout<<"x is 2"; break; default: cout<<"va

if-else equivalent if(x == 1) { cout<<"x is 1"; } else if(x == 2) { cout<<"x is 2"; } else

u

}

}

14

Page 80: COMP 151 Introduction to Algorithms and Programming

For example the weekday/weekend example above could written:

&&day<=7)

if(daycout<<"This is a weekend day";

his is a weekday";

ot a legal day"; However the first example becomes very tedious- there are

rnatives! Consider the following:

day==1)

sday";

y";

";

ice that switch can on used to compare an ants. Therefore we cannot put

labels (for example c ranges (case (1..3):) becau they are not valid C++

onstants. If you need to check ranges or values that are not ncatenation of if and else if statements.

beif(day>=1{

==1||day==7)

else cout<<"T} else cout<<”N

eight alte

if(cout<<"Sunday"; else if(day==2) cout<<"Monday"; else if(day==3) cout<<"Tue. . else if(day==7) cout<<"Saturdaelse cout<<"Not a legal day

Not ly be expression against constvariables s ase n: where n is a variable) or secconstants, use a co

15

Page 81: COMP 151 Introduction to Algorithms and Programming

Common Programming Error • Forgetting a break statement when one is needed in a

is a logic error. • Omitting the space between the word case and the

being tested in a switch statement can mple, writing case3: instead

of writing case 3: simply creates an unused label. n including variables(e.g.,a + b)

in a switch statement’s case label is a syntax error.

ctice

switch statement

integral value cause a logic error. For exa

• Specifying an expressio

Good Programming Pra

In a switch statement that lists the default clause last,

and for symmetry ith other cases.

structures (or) Iteration Structures (or)

the default clause does not require a break statement. Someprogrammers include this break for clarityw RepetitionLooping Structures

as purpose to repeat a statement a certain r while a condition is fulfilled.

types of loops in C++

2. do-while loops 3. for loops

p

Loops havenumber of times o

There are 31. while loops

1. The while loo

(condition)

tatement; }

Its format is: while{ s

• This while loop executes as long as the given logical expression between parentheses is true. When condition is false, execution continues with the statement following the loop block.

16

Page 82: COMP 151 Introduction to Algorithms and Programming

• The condition is tested at the beginning of the loop, so if

peat statement while

it is initially false, the loop will not be executed at all, and its functionality is simply to rethe condition set in expression is true. Two or more number of statements to be repeated then encloses braces { }. Otherwise no need to enclose brace for single statement repetition.

17

Page 83: COMP 151 Introduction to Algorithms and Programming

FousingExam

r example, we are going to make a program to countdown a while-loop: ple Program

tom countdown using while // cus#inusingint m{ int n; cout<<"Enter the starting number"; cin>>n; while(n>0) { cout<<n<<","; --n; } cout<<"FIRE!\n"; return(0); } Output

clude<iostream> namespace std; ain()

Enter the starting number 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3)

18

Page 84: COMP 151 Introduction to Algorithms and Programming

* condition is false: ignore statement and continue after it (to step 5) 3. Execute statement:

the screen and decreases n by 1) lock. Return automatically to step 2

Continue the program right after the block: print FIRE! and ogram.

e must always consider s to end at some point, therefore we must provide

lock some method to force the condition to come false at some point, otherwise the loop will continue

r. In this case we have included --n; that eases the value of the variable that is being evaluated in

e condition (n) by one - this will eventually make the become false after a certain number of

ons: to be more specific, when n becomes 0, that where our while-loop and our countdown end.

course this is such a simple action for our computer performed instantly without any

mbers. Note

cout<<n<<","; --n; (prints the value of n on4. End of b5.end pr

When creating a while-loop, wthat it hawithin the bbelooping forevedecrthcondition (n>0) toloop iteratiis

Of that the whole countdown ispractical delay between nu

: placing semicolon after the while statement, i.e while(); will produce a logical error. 2. The do-while loop Its format is: do {

s, t least one execution of the body

statement; } while(condition);

• Its functionality is exactly the same as the while loopbut guarantees a

19

Page 85: COMP 151 Introduction to Algorithms and Programming

• Two or more number of statements to be repeated thenenc

loses braces { }. Otherwise no need to enclose

atement repetition. brace for single st

For example, the following example program echoes any number you enter until you enter 0. Example Program // number echoer #include<iostream> using namespace std; int main() { unsigned long n; do { cout<<"Enter number (0 to end):";

ut<<"You entered:"<<n<<"\n";

whretur}

cin>>n; co}

ile(n!=0); n(0);

20

Page 86: COMP 151 Introduction to Algorithms and Programming

Output number (0 to end): 12345 ntered: 12345

EnterYou eEnter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever. Note: Forget to place semicolon after the while statement, i.e while() will produce a syntax error. 3. The for loop Its format is: for(initialization;condition;increment)

d its main function is to repeat statement while condition the while loop.

in addition, for loop provides specific locations to contain initialization statement and an increase statement. So this

rm a repetitive action with r which is initialized and increased on each iteration.

orks in the following way: n is executed. Generally it is an initial value

a counter variable. This is executed ly once.

{ statement; } anremains true, like But anloop is specially designed to perfoa counte It w1. Initializatiosetting for on

21

Page 87: COMP 151 Introduction to Algorithms and Programming

2. Condition is checked. If it is true the loop continues, ement is skipped

al, it can be either a single nclosed in braces { }.

ecified in the increase field is e loop gets back to step 2.

otherwise the loop ends and stat(not executed). 3. Statement is executed. As usustatement or a block e4. Finally, whatever is spexecuted and th

Comparison of for and while loops

22

Page 88: COMP 151 Introduction to Algorithms and Programming

Here is an example of countdown using for loop: Example Program // countdown using a for loop #include<iostream> using namespace std; int main() { for(int n=10;n>0;n--) { cout<<n<<","; }

return(0); } Output

cout<<"FIRE!\n";

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write:

23

Page 89: COMP 151 Introduction to Algorithms and Programming

for(;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop: for(n=0,i=100;n!=i;n++,i-- ) { // whatever here...

e for 50 times if either n or i are modified } This loop will executwithin the loop:

n starts with a value of 0, and i with 100, the condition is n!=i

at n is not equal to i). Because n is increased by one and i one, the loop's condition will become false

ter the 50th loop, when both n and i will be equal to 50.

(thdecreased by af

24

Page 90: COMP 151 Introduction to Algorithms and Programming

Nested Loops You can nest loops of any kind inside another to any depth. Example Program //Printing a Triangle #inclu

cout<<"*";

ut<<"\n";

} Output

de<iostream> using namespace std; int main() { for(int i=1;i<=5;i++) {

for(int j=1;j<=i;j++) {

} co} return(0);

* ** *** **** ***** Jumping statements . The break statement1

Using break we can leave a loop even if the condition r its end is not fulfilled. It can be used to end an infinite op, or to force it to end before its natural end. or example, we are going to stop the count down before its atural end (maybe because of an engine check failure?): xample Program

foloFnE break loop example include<iostream> sing namespace std;

//#u

25

Page 91: COMP 151 Introduction to Algorithms and Programming

int main() { int n; for(n=10; n>0; n--) { cout<<n<< ", ";

if(n==3) {

wn aborted!"; break;

} retur}

cout<<"countdo

}

n(0);

Output 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

tinue statement2. The con The continue statement causes the program to skip the

he loop in the current iteration as if the end of the atement block had been reached, causing it to jump to the rt of the following iteration. example, we are going to skip the number 5 in our tdown: ple Program

rest of tststaFor counExam

using

//continue loop example#include<iostream>

namespace std; int main() { for(int n=10; n>0; n--) { if(n==5) continue; cout<<n<< ", "; } cout<<"FIRE!\n";

26

Page 92: COMP 151 Introduction to Algorithms and Programming

return(0); } Output

, 1, FIRE!

tement

10, 9, 8, 7, 6, 4, 3, 2 3. The goto sta

ws to make an absolute jump to another point in the program. You should use this feature with caution since conditional jump ignoring any type of nesting limitations.

The destination point is identified by a label, which is as an argument for the goto statement. A label is

ade of a valid identifier followed by a colon (:) erally speaking, this instruction has no concrete

mming aside from ing fans may find for it.

For e

Goto allo

its execution causes an un

then used m

Genuse in structured or object oriented prograthose that low-level programm

xample, here is our countdown loop using goto: Example Program //goto loop example #include<iostream> using namespace std; int main() { int n=10; loop: cout<<n<<","; n--; if(n>0)

ut<<"FIRE!\n";

utput

goto loop; coreturn(0); } O

3, 2, 1, FIRE! 10, 9, 8, 7, 6, 5, 4,

27

Page 93: COMP 151 Introduction to Algorithms and Programming

Exercises 1. Write an if statement that prints YES if a variable age is

ater than 21. - 2 Marks t that displays YES if a

variable age is greater than 21, and displays NO - 2 Marks

3.

- 2 Marks 5. t least how many times the loop body is executed in a

OWN

r even - 2 Marks

to find the factorial of a given number - 2 Marks that displays the following set of

- 2 Marks 60 70 80 90 100

11. Write a program to find sum, difference, multiply and on of given two numbers using switch case

elective structure - 3 Marks icity board charges the following rates to

domestic users to discourage large consumption of ergy: For the first 100 units – 10 Paisa per unit

For next 200 units – 20 Paisa per unit nd 300 units – 30 Paisa per unit

total cost is more than 10 OMR then an additional surcharge of 15% is added.

te a program to print the consumed unit and total it. - 3 Marks

gre2. Write an if…else statemen

otherwise Write a for loop that displays the number from 100 to 110. Thank You - 2 Marks

4. Write a while loop that displays the number from 500 to 520. Ado…while loop? - 1 Mark

6. Write a switch statement that prints YES if a variable ch is ‘y’, prints NO if ch is ‘n’, and prints UNKNotherwise - 2 Marks

7. Write a program to find the biggest among three given numbers - 2 Marks

8. Write a program to find the given number is odd o9. Write a program

by using for loop10. Write a for loop

numbers 0 10 20 30 40 50

divisis

12. An electr

en BeyoIf the

Wriamount for the consumed un

28

Page 94: COMP 151 Introduction to Algorithms and Programming

13. Write a Program to find the GCD of two numbers by

14 g

using while loop structure - 2 Marks . Write a program to calculate and Print the Followintable by using for loop structure - 3 Marks1*2=2 2*2=4 3*2=6 4*2=8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18 10*2=20

29

Page 95: COMP 151 Introduction to Algorithms and Programming

CHAPTER – 5

FUNCTIONS

Page 96: COMP 151 Introduction to Algorithms and Programming

Functions are used to modularize code or sort it into different blocks or sub-tasks. Functions perform a particular job that the programmer assigns it to do. They make code look neater and more elegant and can be "called" or used as many times as you like. Statements in function bodies are written only once and reused from several locations of a program. It enables the divide and conquer technique. It is called as methods or procedure in other language.

We are going to discuss two types of Functions 1. User Defined Functions 2. Library Functions (or) Predefined Functions

1. User Defined Functions Example program for Simple Function #include<iostream> using namespace std; void starline(); //Function Declaration (or) Prototype int main() { cout<<"Program for Function \n"; starline(); //Call to Function starline cout<<"This is the simple Program\n "; starline(); //Call to Function starline cout<<"Printing Star line to decorate the output\n"; starline(); //Call to Function starline return(0); } void starline() //Function definition { int j; for(j=0;j<45;j++) { cout<<"*"; } cout<<endl; }

2

Page 97: COMP 151 Introduction to Algorithms and Programming

Output Program for Function ********************************************* This is the simple Program ********************************************* Printing Star line to decorate the output ********************************************* In C++, Function has 3 parts

1. Function declaration (or) Prototype 2. Function Call 3. Function definition

1. Function Declaration (or) Prototype

Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function without telling the compiler about it. The most common approach is to declare the function at the beginning of the program. In the above program the function starline() is declared in the line void starline();

The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parenthesis indicate that it takes no arguments (or) parameters. Function declarations are also called prototypes, since they provide a model (or) blueprint for the function. They tell the compiler, “a function that looks like this is coming up later in the program. Note: The function declaration is terminated with a semicolon.

3

Page 98: COMP 151 Introduction to Algorithms and Programming

2. Function Call The function is called (or) invoked (or) executed three times from main(). Each of the three calls looks like this: starline(); The syntax of the function call is: The function name followed by the parenthesis. This is very similar to that of the declaration, except that the return type is not used. The call is terminated by a semicolon. Executing the call statement causes the function to execute; that is, control is transferred to the statement in the function definition are executed, and then control returns to the statement following the function call. 3. Function Definition Finally we come to the function itself, which is referred to as the function definition. The definition contains the actual code for the function. Here’s the definition for starline(); void starline() //declarator (or) header { for(int j=0;j<45;j++) // function body { cout<<’*’; } cout<<endl; } The definition consists of a line called the declarator (or) header, followed by the function body. The function body is composed of the statements that make up the function, delimited by braces. The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order (if there are arguments), and have the same return type.

4

Page 99: COMP 151 Introduction to Algorithms and Programming

Notice that the declarator is not terminated by a semicolon. When the function is called, the control transferred to the first statement in the function body. The other statements in the function body are then executed, and when the closing brace is encountered, the control returns to the calling program.

Function Components S.NO Components Purpose Example 1 Declaration

(Prototype) Specifies function name, argument types, and return value. Alerts compiler(and programmer) that function definition is coming up later

void func();

2 Call Causes the function to be executed

func();

3 Definition Body of the function. Contains the lines of code that constitute the function

void func() { -------;//lines of code -------; }

4 Declarator (or) Header

First line of definition

void func()

Common Programming Error A function is invoked (or) called before it is defined (body), and that function does not have a function prototype, a compilation error occurs.

5

Page 100: COMP 151 Introduction to Algorithms and Programming

Note: If a function is defined before it is invoked, then the function’s definition also serves as the function’s prototype, so a separate prototype is unnecessary. Example Program #include<iostream> using namespace std; /*Function definition before it is called (or) invoked So no need of prototype (or) declaration*/ void starline() { int j; for(j=0;j<45;j++) { cout<<"*"; } cout<<endl; } int main() { cout<<"Program for Function \n"; starline(); //Call to Function starline cout<<"This is the simple Program\n "; starline(); //Call to Function starline cout<<"Printing Star line to decorate the output\n"; starline(); //Call to Function starline return(0); } Good Program Practice In general for the good program practice do the declaration (or) prototype of the function, then main() function followed by definition of function.

6

Page 101: COMP 151 Introduction to Algorithms and Programming

Passing Parameters (or) Arguments to Functions When a function is called, the program may send values into the function. Values that are passed into a function are called actual arguments (or) actual parameter. The variables that receive these values in function definition are called formal arguments (or) formal parameters. Functions with Empty Parameter List

– Specified by writing either void or nothing at all in parentheses

– For example, void print(); (or) void print(void); Specifies that function print does not take arguments and does not return a value Example Program #include<iostream> using namespace std; void function1(); void function2(void);

Specify an empty parameter list by putting nothing in the parentheses

Specify an empty parameter list by putting void in the parentheses int main()

{ function1(); function2(); return(0); } void function1() { cout<<”function 1 takes no arguments”<<endl; } void function2(void) { cout<<”function 2 also takes no arguments”<<endl; }

7

Page 102: COMP 151 Introduction to Algorithms and Programming

Output function 1 takes no arguments function 2 also takes no arguments Two ways to pass arguments to functions

1. Pass-by-Value 2. Pass-by-Reference 1. Pass-by-Value When an actual argument is passed into a formal argument, only a copy of the actual argument’s value is passed. Changes to the formal arguments do not affect the actual arguments. Value given in actual argument is straight value (or) value passed through variable Example 1: actual arguments are straight values #include<iostream> using namespace std; in function prototype void repchar(char,int); only arguments int main() data type is enough { repchar(‘-‘,45); Actual arguments repchar(‘*’,25); return(0); } Formal arguments void repchar(char ch,int n) { for(int j=0;j<n;j++) { cout<<ch; } cout<<endl; } Output --------------------------------------------- *************************

8

Page 103: COMP 151 Introduction to Algorithms and Programming

Example 2: Actual arguments are given through variable #include<iostream> using namespace std; in function prototype void repchar(char,int); only arguments int main() data type is enough { char chin; int nin; cout<<”Enter a character”<<endl cin>>chin; cout<<”Enter number of times to repeat it”<<endl; cin>>nin; repchar(chin,nin); Actual arguments return(0); } void repchar(char ch,int n) Formal arguments { for(int j=0;j<n;j++) { cout<<ch; } cout<<endl; }

Output Enter a character * Enter number of times to repeat it 5 *****

2. Pass-by-Reference When the actual arguments passed to the formal

arguments, the reference variables (used in function declarator (or) header) allow the function to access the actual argument’s original values (not copy). Changes in

9

Page 104: COMP 151 Introduction to Algorithms and Programming

the formal arguments in function body will affect the actual arguments.

C++ provides a special type of variable called a reference variable that used as a formal argument allows access to the original values of actual arguments. A reference variable is an alias for another variable. Any changes made to the reference variable are actually performed on the variable for which it is an alias.

Reference variables are declared like regular variables, except you have to place an ampersand (&) symbol in front of the name.

Example Program #include<iostream> int squarebyvalue(int); void squarebyref(int&); using namespace std; int main() { int x=2; int z=3; int y; cout<<"Before square by value call x value is"<<x<<endl; y=squarebyvalue(x); cout<<"After square by value call x value is"<<x<<endl; cout<<"After square by value call y value is"<<y<<endl; cout<<"Before square by reference call z value is"<<z<<endl; squarebyref(z); cout<<"After square by reference call z value is"<<z<<endl; return(0); } int squarebyvalue(int a) { a=a*a; return(a); }

10

Page 105: COMP 151 Introduction to Algorithms and Programming

void squarebyref(int &b) { b=b*b; } Output Before square by value call x value is2 After square by value call x value is2 After square by value call y value is4 Before square by reference call z value is3 After square by reference call z value is9 Returning Values From Functions:

When function completes its execution it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. When a function returns a value, the data type of this return value must be specified.

In the above example squarebyvalue() function returns an integer value to the calling program. So the return type integer is specified before the function name in declaration and in definition. Example Program #include<iostream> using namespace std; float convert(float); int main() { float pound,kg; cout<<”Enter your weight in pounds”<<endl; cin>>pound; kg=convert(pound); cout<<”Your weight in Kilograms is”<<kg; return(0); }

11

Page 106: COMP 151 Introduction to Algorithms and Programming

float convert(float p) { float k; k=0.453592*p; return(k); } Output Enter your weight in pounds 45.7 Your weight in Kilograms is20.7292

2. Library Functions (or) Predefined Functions Example: Math Library Functions (or) Math pre-defined Functions

Function Description Example

ceil( x ) rounds x to the smallest integer not less than x

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x ( x in radians)

cos( 0.0 ) is 1.0

xponential function ex exp( 1.0 ) is 2.71828 ex

e exp( x )

p( 2.0 ) is 7.38906 olute value of x fabs( 5.1 ) is 5.1

fa

abs fabs( x )

bs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76

oor( x ) fl rounds x to the largest integer not greater than x

floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

od( x, y ) fm remainder of x/y as a floating-point num ber

fmod( 2.6, 1.2 ) is 0.2

log( x ) natural logarithm of x (base e)

log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0

g10( x ) lo logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0

pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128 pow( 9, .5 ) is 3

sin( x ) trigonometric sine of x (x in radians)

sin( 0.0 ) is 0

sqrt( x ) square root of x (where x is a sqrt( 9.0 ) is 3.0 nonnegative value)

tan( x ) trigonometric tangent of x (x in radians) 12

tan( 0.0 ) is 0

Page 107: COMP 151 Introduction to Algorithms and Programming

In the above figure, the variables x and y are of type double. These are the predefined functions for mathematical calculations. These functions are global functions and are placed in header file <cmath> or <math>, so that the global functions can be reused in any program that includes the header file <cmath> or <math>. Example Program #include<iostream> #include<cmath> using namespace std; int main() { double x,y; x=12.45; y=1.9; cout<<”Output of ceil function”<<ceil(x)<<endl; cout<<”Output of floor function”<<floor(x)<<endl; cout<<”Output of exp function”<<exp(x)<<endl; cout<<”Output of pow function”<<pow(x,y)<<endl; cout<<”Output of sqrt function”<<sqrt(x)<<endl; cout<<”Output of fabs function”<<fabs(x)<<endl; cout<<”Output of fmod function”<<fmod(x,y)<<endl; cout<<”Output of log function”<<log(x)<<endl; cout<<”Output of log10 function”<<log10(x)<<endl; cout<<”Output of sin function”<<sin(x)<<endl; cout<<”Output of cos function”<<cos(x)<<endl; cout<<”Output of tan function”<<tan(x)<<endl; return(0); } Output Output of ceil function13 Output of floor function12 Output of exp function255250 Output of pow function120.454

13

Page 108: COMP 151 Introduction to Algorithms and Programming

Output of sqrt function3.52846 Output of fabs function12.45 Output of fmod function1.05 Output of log function2.52172 Output of log10 function1.09517 Output of sin function-0.116108 Output of cos function0.993237 Output of tan function-0.116899 Scope of Variables: All the variables that we intend to use in a program must have been declared with its type specifier. A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. #include<iostream> using namespace std; int a; char name[50]; Global variables unsigned int numberofsons; int main() { unsigned int age; Local Variables float average,percentage; cout<<”Enter your age:”; cin>>age; Instructions … } Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

14

Page 109: COMP 151 Introduction to Algorithms and Programming

The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa. Example Program #include<iostream> using namespace std; void fun(); int temp=0; //global variable int main() { int x=15;//local variable to main cout<<"The value of x is"<<x<<endl; temp=temp+x; cout<<"Value of temp in main"<<temp<<endl; fun(); return(0); } void fun() { int a=25;//local variable to fun cout<<"Value of a is"<<a<<endl; temp=temp+a; cout<<"Value of temp in fun"<<temp<<endl; } Output The value of x is15 Value of temp in main15 Value of a is25 Value of temp in fun40

15

Page 110: COMP 151 Introduction to Algorithms and Programming

Unary scope resolution operator (::) • Used to access a global variable when a local variable

of the same name is in scope • Cannot be used to access a local variable of the same

name in an outer block Example Program #include<iostream> using namespace std; int number=100; int main() { int number=45; int a=10; cout<<"Value of local variable number in main"<<number<<endl; if(a>0) { int number=10; cout<<"The value of number in if statement is"<<number<<endl; cout<<"Value of global variable number is"<<::number<<endl; } number=number*2; cout<<"Value of local variable number in main"<<number<<endl; ::number=::number+100; cout<<"Value of global variable number is"<<::number<<endl; return(0); } Output Value of local variable number in main45 The value of number in if statement is10 Value of global variable number is100 Value of local variable number in main90 Value of global variable number is200

In the above program main function uses two variable named number. The scope of the first variable number is start from the beginning of main function, and the scope of

16

Page 111: COMP 151 Introduction to Algorithms and Programming

second variable number is starting inside if block. The second variable number scope is only within if block. So inside if block number is 10. At that time the global variable number and the first variable number in main function are hided. After if block, number means, it is the first variable number in main. At that time the global variable number is hided. So with the help of unary scope resolution operator we can access the global variable number inside main function. But we can’t use unary scope resolution operator to access the variable number from if block. This will produce an error message. Good Programming Practice

• Always using the unary scope resolution operator (::) to refer to global variables makes programs easier to modify by reducing the risk of name collisions with non-global variables.

• Avoid using variables of the same name for different purposes in a program. Although this is allowed in various circumstances but, it can lead to errors.

Exercises 1. Write a program with a print function to display your

favorite colors. Choose a name for the function that tells what it does. - 2 Marks

2. Write a program with two print functions and call them each from the main function. Write one function to list your favorite foods and another to list your hobbies. - 2 Marks

3. Write a program using a print function to print a right triangle made out of stars (*) which is five stars high and five stars wide at the base of the triangle. - 2 Marks

17

Page 112: COMP 151 Introduction to Algorithms and Programming

4. What would the following function do? - 2 Marks void example(int n) { int i; for (i=0; i<n; i++) cout<<'*'; cout<<endl; } How would you call this function in a program? How would you use this function in producing the following output on the screen? * ** *** ****

5. Check the following two programs are correct or not. If it is correct what would be the output of these two programs?

- 2 Marks a)

#include<iostream> using namespace std; void change(void) { int x; x=1; } int main() { int x; x=0; change(); cout<<x<<endl; return(0); }

18

Page 113: COMP 151 Introduction to Algorithms and Programming

b) #include<iostream> using namespace std; void change(int x) { x=1; cout<<x<<endl; }

int main() { int x; x=0; change(x); cout<<x<<endl; return(0); }

6. Write a function prototype for a function that takes two parameters of type float and returns true (1) if the first parameter is greater than the second and otherwise returns false (0). - 1 Mark

7. How is information supplied as input to a function? How

can information be conveyed back to the calling program? - 1 Mark

8. Check the following program is correct or not. If it is correct what would be the output of the program? - 2 Marks #include<iostream> using namespace std; void change(int &y) { y=1; }

19

Page 114: COMP 151 Introduction to Algorithms and Programming

int main() { int x; x=0; change(x); cout<<x<<endl; return(0); }

9. If a function doesn't return a value, what type should it be

declared? - 1 Mark 10. What must be the first line of a function definition, and

what information does it contain? - 1 Mark 11. How many values can be returned from a function?

- 1 Mark 12. What is the significance of empty parenthesis in a

function declaration? - 1 Mark 13. True or False: When a function returns a value, the

entire function call can appear on the right side of the assignment statement and be assigned to another variable on the left side. - 1 Mark

14. True or False: When actual arguments are passed by

value, only the copy of the actual arguments are sent to the formal arguments and later changes on the formal arguments will affect the actual arguments. - 1 Mark

15. Where is a function’s return type specified? - 1 Mark

20

Page 115: COMP 151 Introduction to Algorithms and Programming

16. Regarding Overloaded functions which of the following statement(s) is(are) true. - 1 Mark

a). are group of functions with the same name and all have the same number and types of arguments b). make life simpler for programmers c). are group of functions doing the same work with different names. d). all have the same number and types of arguments with different return types. e). are group of functions with the same name and all have the different number, different sequence and different types of arguments.

17. Write declarations for two overloaded functions named bar(). They both return type int. The first takes one argument of type char, and the second takes two arguments of type char. If this is impossible, say why?

- 1 Mark 18. Write a declaration for a function called blyth() takes

two arguments and return type char. The first argument is type int, and the second is type float with a default value of 3.14159 - 1 Mark

19. Write a function called zerosmaller() that is passed two

int arguments by reference and then sets the smaller of the two numbers to 0(zero). Write a main() program to execute this function. - 2 Marks

20. Write a function called circarea() that finds the area of a

circle. It should take an argument of type float and return an argument of the same type. Write a main() function that gets a radius value from the user, calls circarea(), and displays the result. - 2 Marks

21

Page 116: COMP 151 Introduction to Algorithms and Programming

21. Check the following program is correct or not. If it is correct what would be the output of the program? - 2 Marks #include<iostream> using namespace std; void square(int); int c=3; int main() { int a=1; int c=12; c=c/2; cout<<"The value of c is"<<c<<endl; square(c); square(::c); if(a<10) { int c=44; cout<<"The value of c is"<<c<<endl; } c++; cout<<"The value of c is"<<c<<endl; ::c=::c+5; cout<<"The value of c is"<<::c<<endl; return(0); }

void square(int x) { int c; c=x*x; cout<<"The value of c is"<<c<<endl; ::c++; cout<<"The value of c is"<<::c<<endl; }

22

Page 117: COMP 151 Introduction to Algorithms and Programming

CHAPTER – 6

ARRAYS

1

Page 118: COMP 151 Introduction to Algorithms and Programming

An array is a group of elements of the same type that are placed in contiguous memory locations. In general, only the array itself has a symbolic name, not its elements. Each element is identified by an index which denotes the position of the element in the array. Arrays are suitable for representing composite data which consist of many similar, individual items. Examples: a list of names, a table of world cities and their current temperatures, or the monthly transactions for a bank account. The number of elements in an array is called its dimension. The dimension of an array is fixed and predetermined. It cannot be changed during program execution. In this array we will discuss

1. One dimensional Array 2. Two dimensional Array

One Dimensional Array Array DeclarationC++ Arrays can be declared for all c++ data types (int, float, double, char etc…). All the elements are stored in consecutive memory locations. The elements can be accessed by using the position (or) index. Declaring C++ Arrays of int type: The c++ arrays are declared with the data type name and the number of elements inside the square brackets. int varname[50]; // C++ Array of type int with maximum size=50. The above declaration means, the varname is an array of integer type. The values inside this varname array can be accessed by referring to the position of their elements like varname[0], varname[1] etc.,

2

Page 119: COMP 151 Introduction to Algorithms and Programming

All the C++ arrays are based on Zero index values. That means the position reference starts at 0(Zero) and counts till the n-1th position. So in the above array, 50 elements can be stored starting from 0 to 49. The maximum number of elements that can be stored or the maximum size of the c++ array is 50. Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. Example Program The values can be stored and accessed as given in the following code fragment. #include<iostream> using namespace std; int main() { int a[5]; a[0]=10; a[1]=20; cout<<"Enter the value for third element"<<endl; cin>>a[2]; a[0]=a[0]*5; cout<<a[0]<<"\t"<<a[1]<<"\t"<<a[2]<<endl; return(0); } Output Enter the value for third element 30 50 20 30 Note: Care should be taken while using or referring to the position of the element. The position reference should not exceed the maximum size specified in the declaration. If it exceeds, the program will not generate any compiler errors. But it will raise run time errors and exceptions.

3

Page 120: COMP 151 Introduction to Algorithms and Programming

Declaring C++ arrays of type float: The declaration and use of c++ arrays in float type are the same as int. The declaration is written as follows. float varname[100]; //A c++ array of float type The above declaration means, the c++ float array contains 100 elements starting from position 0 till 99. The elements can be accessed as varname[0], varname[1], varname[2] … varname[99]. Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. The values can be stored and accessed as given in the following code fragment. varname[0]=10.05; varname[1]=11.04; varname[2]=13.34; cout<<"Enter the value for fourth element"<<endl; cin>>varname[3]; cout<<varname[0]<<endl; Declaring C++ arrays of type char: This is one of the most widely used and problematic type of c++ array. When an array of char is declared, this char array can be used as a string with the maximum size as specified in the array declaration. char varname[50]; //Memory reserved for 50 characters. The above declaration means, the c++ char array contains 50 elements starting from position 0 till 49. The elements can be accessed as varname[0], varname[1], varname[2] … varname[49].

4

Page 121: COMP 151 Introduction to Algorithms and Programming

Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. The values can be stored and accessed as given in the following code fragment. varname[0]='a'; cout<<"Enter the character for second element"<<endl; cin>>varname[1]; cout<<varname[0]<<endl; cout<<varname[1]<<endl; C++ Array Advantages:

Easier to declare and use. Can be used with all data types.

C++ Array Disadvantages: Fixed size data. If the number of elements stored are

less than the maximum size, then the rest of the memory space goes waste.

If the number of elements to be stored are more than the maximum size, the array cannot accommodate those new values.

Initialization of Integer, Float and Char types of Array If a programmer wants to initialize an array elements it can be done by specifying the values enclosed within braces { }. For example, using the array age, if a programmer wants to initialize integer values 55, 35, 30, 40 respectively to each of the array positions it can be written. int age[4]={55,35,30,40}; So the above arrays would take values as below

5

Page 122: COMP 151 Introduction to Algorithms and Programming

age [0] [1] [2] [3]

values 55 35 30 40

If a programmer wants to initialize float values 34.5, 23.4, and 45.6 in the array temperature then the initialization can be written as float temperature[3]={34.5,23.4,45.6}; So the above arrays would take values as below

temperature [0] [1] [2]

values 34.5 23.4 45.6

If a programmer wants to initialize char values ‘e’, ‘f’, ‘g’, ‘y’ in the array name then the initialization can be written as char name[5]={‘e’,’f’,’g’,’y’,’\0’}; When initializing the array of characters, a special character (the null character) is used to signal the end of the string. The null character can be written as '\0' (backslash, zero). So the above arrays would take values as below

Note: One interesting fact is that the size of the array element can also be left blank, in which case the array takes the size of the array as the number of elements initialized within { }.

name [0] [1] [2] [3] [4]

values ‘e’ ‘f’ ‘g’ ‘y’ ‘\0’

For example if the array takes the form as int age[ ]={55,35,30,40,50};

6

Page 123: COMP 151 Introduction to Algorithms and Programming

Then the size of the array age is 5 which is the number of elements initialized within { }. float temperature[ ]={34.5,23.4,45.6,28.9}; Then the size of the array temperature is 4 which is the number of elements initialized within{ }. char name[ ]={‘s’,’a’,’y’,’\0’}; Then the size of the array name is 4 which is the number of elements initialized within{ }. In C++ array of characters is called as string. A string or array of characters can be initialized without specifying the single quote inside{ }. But like a string literals it should be given within double quote. Example: char sen[ ]="c++ char array string example"; In this second case, when using double quotes (") for initialization, the null character ‘\0’ is appended automatically. Note: When declaring array without initialization, the size should be mentioned in [ ]. Example: int age[ ]; is not the proper declaration. The compiler will generate the error as size should be mentioned. Like the above examples, the c++ arrays can be declared with or without initializing values.

7

Page 124: COMP 151 Introduction to Algorithms and Programming

Accessing Array Elements through For loop In an array, the index values are starts from 0 and it is increasing one by one up to the maximum size of the array. So to get the input values in an array or to display the content of the array, we can use for loop. Without for loop, manipulating the array is difficult. Almost always need to use a for loop to step through the array elements. Example Program /*Program to read the input for an array through for loop and to display the content of the array through for loop*/ #include<iostream> using namespace std; int main() { int a[10],i; //To read the input for array for(i=0;i<10;i++) { cout<<"Enter the Value for a["<<i<<"]"<<endl; cin>>a[i]; } //To display the content of the array for(i=0;i<10;i++) { cout<<"Value of a["<<i<<"] is"<<a[i]<<endl; } return(0); } Output Enter the Value for a[0] 11 Enter the Value for a[1] 345 Enter the Value for a[2] 15

8

Page 125: COMP 151 Introduction to Algorithms and Programming

Enter the Value for a[3] 3 Enter the Value for a[4] 56 Enter the Value for a[5] 27 Enter the Value for a[6] 90 Enter the Value for a[7] 41 Enter the Value for a[8] 12 Enter the Value for a[9] 77 Value of a[0] is11 Value of a[1] is345 Value of a[2] is15 Value of a[3] is3 Value of a[4] is56 Value of a[5] is27 Value of a[6] is90 Value of a[7] is41 Value of a[8] is12 Value of a[9] is77 Note Without using for loop, array of characters (or) string can be manipulated. This is allowed in c++. But, int and float arrays are always manipulated through for loop. Example Program #include <iostream> using namespace std; int main () { char question[ ] = "Please, enter your first name:"; char greeting[ ] = "Hello ";

9

Page 126: COMP 151 Introduction to Algorithms and Programming

char fname[80]; cout<<question; cin>>fname; cout<<greeting<<"Your First name is..."<<fname; return(0); } Output Please, enter your first name:Salim Hello Your First name is...Salim In the above example to read the values in fname char array, for loop is not used. Simply the array name, fname is given with cin. Also, to display the content of the fname char array, for loop is not used. Simply the array name, fname is given with cout. Note: When giving input to the char array without for loop, only the characters other than blank space are allowed. If the blank space is given as input from keybord, which means it’s the end of array. So after blank space whatever given as the input, it is not stored in the char array. So in this case, only a single word is allowed as the input to the char array. Passing arrays to Functions At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation. In order to pass arrays as parameters to a function, the function declaration is specified as in the following example. void display(int[ ]);

10

Page 127: COMP 151 Introduction to Algorithms and Programming

That is the above function display takes the int type of array as a parameter. In function declaration the array data type is followed by empty [ ]. This is enough to specify in the declaration. No need to specify the array name. Example Program #include<iostream> using namespace std; void print(int[ ],int); int main() { int a[20],n,i; cout<<"Enter the number of elements in the array"<<endl; cin>>n;

for(i=0;i<n;i++) { cout<<"Enter Value for a["<<i<<"]"<<endl; cin>>a[i]; }

print(a,n);

for(i=0;i<n;i++) { cout<<"Value of a["<<i<<"] is"<<a[i]<<endl; }

return(0); } void print(int b[ ],int m) { int i;

for(i=0;i<m;i++) { cout<<"Value of b["<<i<<"] is"<<b[i]+1<<endl; }

}

11

Page 128: COMP 151 Introduction to Algorithms and Programming

Output Enter the number of elements in the array 3 Enter Value for a[0] 11 Enter Value for a[1] 22 Enter Value for a[2] 33 Value of b[0] is12 Value of b[1] is23 Value of b[2] is34 Value of a[0] is11 Value of a[1] is22 Value of a[2] is33 The print() function is declared before the main(), with the first parameter is an int type of array, and the second parameter is an int type of variable. A int type of array a[20] is declared inside the main() and the input for the array is read out through the for loop. Then this array a is passed as the first parameter to print(). In print() call only the array name a is specified. No need to specify the size. The second parameter is used to get the number of elements in the array, and it is passed to the print() call. In c++ the set of values are passed as a parameter through array concept When receiving the array values in the print() body, another int type of array b[ ] is specified with empty [ ]. The first value a[0] is copied to b[0] and so on up to the last element of the array. So whatever changes in the array b[ ], inside the body of print() will not affect the values of array a[ ] in the main(). So after the print() call, the values in array a[ ] is not changed in main().

12

Page 129: COMP 151 Introduction to Algorithms and Programming

Exercises 1. Write a C++ program to read 10 integer numbers in

an array and find the sum of these numbers. 2. Write a C++ program to read and print your first

name, middle name and Family name. 3. Write a C++ program to read 10 floating point

numbers in an array and pass this array to a function named sum(), which calculates the sum of these numbers and print the sum.

13