0% found this document useful (0 votes)
20 views102 pages

Project (1) - Compressed

The document outlines a computer programming lab focused on flowcharts, pseudocode, and C++ programming concepts. It includes exercises for writing pseudocode, learning about variables, types, arithmetic operators, and input/output operations in C++. Additionally, it provides practice problems and tasks for students to apply their knowledge in programming.

Uploaded by

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

Project (1) - Compressed

The document outlines a computer programming lab focused on flowcharts, pseudocode, and C++ programming concepts. It includes exercises for writing pseudocode, learning about variables, types, arithmetic operators, and input/output operations in C++. Additionally, it provides practice problems and tasks for students to apply their knowledge in programming.

Uploaded by

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

Lab 1: Computer Programming

Flow Charts and Pseudo Codes

Flowcharts
Lab 1: Computer Programming
Flow Charts and Pseudo Codes

Example: Add two numbers entered by the user.


Lab 1: Computer Programming
Flow Charts and Pseudo Codes
Lab 1: Computer Programming
Flow Charts and Pseudo Codes
Pseudocodes

Excersie 1 (Pseudocode):

Write pseudo Code to read a student's three grades, calculate the average of the grades, then
display the average grade.

Solution:

BEGIN DECLARE grade1, grade2, grade3 AS FLOAT


DECLARE average AS FLOAT
PRINT "Enter first grade: "
READ grade1
PRINT "Enter second grade: "
READ grade2
PRINT "Enter third grade: "
READ grade3
SET average = (grade1 + grade2 + grade3) / 3
PRINT "The average grade is: " + average
END

Tasks:

Write Pseudocodes for rest of the exercises.


109304 – Computer Programming
Faculty of Electrical Engineering

Engr. Muhammad Asad

Syed Ali Irtaza, Ph.D.


Assistant Professor (EE)
Institute of Space Technology, Islamabad
syed.ali@ist.edu.pk, Islamabad
Lab 2 Variables, Inputs/Outputs and Arithmetic Operators

2.1. Objectives:

• To learn and to use Variables


• Variable Types
• Declaring Variables
• Arithmetic Operators
• Comments
• Input/output in C++

2.2. Outcomes:

Students should be able to know C++ variables their types and arithmetic operators.
• Students should be able to use cin and cout methods in the programs.
2.3. Variables, Types and Operators

A variable is a place to store a piece of information. Just as you might store a friend's phone number
in your own memory, you can store this information in a computer's memory. Variables are your
way of accessing your computer's memory.
C++ imposes fairly strict rules on how you can name your variables:
• variable names must begin with a letter
• variable names are "case-sensitive" (i.e., the variable "myNumber" is different from
the variable "MYNUMBER" which is different from the variable "mYnUmBeR")
• variable names can't have spaces
• variable names can't have special characters (typographic symbols)

What can you name your variables? In general, variable names can be composed of letters,
numbers, and underscores (_).
Keywords: C++ reserves certain names which have special meaning to the language, and you are
not allowed to use any of these keywords as variables names. Some examples of C++ keywords
are int, for, else, and class. You can, however, use keywords in the middle of a variable name,
such as "foreign" or "classical".

2.4. Variable Types

The values of variables are stored somewhere in an unspecified location in the computer memory as
zeros and ones. Our program does not need to know the exact location where a variable is stored; it
can simply refer to it by its name. What the program needs to be aware of is the kind of data stored in
the variable. It's not the same to store a simple integer as it is to store a letter or a large floating-point
number; even though they are all represented using zeros and ones, they are not interpreted in the same
way, and in many cases, they don't occupy the same amount of memory.
Fundamental data types are basic types implemented directly by the language that represent the
basic storage units supported natively by most systems. They can mainly be classified into:


Character types: They can represent a single character, such as 'A' or '$'. The most basic
type is char, which is a one-byte character. Other types are also provided for wider
characters.

Numerical integer types: They can store a whole number value, such as 7 or 1024. They
exist in a variety of sizes, and can either be signed or unsigned, depending on whether they
support negative values or not.

Floating-point types: They can represent real values, such as 3.14 or 0.01, with different
levels of precision, depending on which of the three floating-point types is used.

Boolean type: The boolean type, known in C++ as bool, can only represent one of two
states, true or false.

Here is the complete list of fundamental types in C++:


Group Type names* Notes on size / precision
char Exactly one byte in size. At least 8 bits.
char16_t Not smaller than char. At least 16 bits.
Character types char32_t Not smaller than char16_t. At least 32 bits.

wchar_t Can represent the largest supported character


set.
signed char Same size as char. At least 8 bits.
signed short int Not smaller than char. At least 16 bits.
Integer types (signed) signed int Not smaller than short. At least 16 bits.
signed long int Not smaller than int. At least 32 bits.
signed long long int Not smaller than long. At least 64 bits.
unsigned char
unsigned short int
Integer types unsigned int
(same size as their signed counterparts)
(unsigned) unsigned long int
unsigned long
long int
float
Floating-point types double Precision not less than float
long double Precision not less than double
Boolean type bool
Void type void no storage
Null pointer decltype(nullptr)

2.5. Declaring Variables

Declaring a variable in C++ is simple. Let's say you want to declare a variable of type int
called myAge.
That is to say, the variable myAge will store an integer. In C/C++, this is written:
Int myAge;
All this does is tell the computer that you plan to use an integer, and that the integer's name is
myAge. In some languages, variables are initialized to 0 - that is, a variable's initial value will be
0. This is not true of C++! Sometimes your variables will be initialized to 0, but sometimes they
will be initialized with garbage. As you might anticipate, this can cause some nasty bugs. Hence,
it is always a good idea to initialize your variables with some value. If you don't know what a
variable's initial value should be, initialize it to 0.

Example 1:
Let‘s write a program that stores your age in a variable and outputs ―My age is 21". The first line
of the main function initializes myAge by assigning it a value immediately. compile and run the
following code
Code:

#include<iostream>
using namespace std;
int main()
{
Int myAge = 21;
cout<<"My age is “<<myAge<<“years”;
return 0;
}

2.6. Introduction to strings

Fundamental types represent the most basic types handled by the machines where the code may
run. But one of the major strengths of the C++ language is its rich set of compound types, of
which the fundamental types are mere building blocks. An example of compound type is the
string class. Variables of this type are able to store sequences of characters, such as words or
sentences. A very useful feature! A first difference with fundamental data types is that in order to
declare and use objects (variables) of this type, the program needs to include the header where
the type is defined within the standard library (header <string>):

Code:

// my first string
#include <iostream>
using namespace std;
int main ()
{
string mystring;
mystring = "This is a string";
cout << mystring;
return 0;
}
As you can see in the previous example, strings can be initialized with any valid string literal, just
like numerical type variables can be initialized to any valid numerical literal. As with fundamental
types, all initialization formats are valid with strings:

string mystring = "This is a string";


string mystring ("This is a string");
string mystring {"This is a string"};

Strings can also perform all the other basic operations that fundamental data types can, like being
declared without an initial value and change its value during execution:

Example:

// my first string
#include <iostream>
#include <string>
using namespace std;

int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}

Note: inserting the endl manipulator ends the line (printing a newline character and
flushing the stream).
The string class is a compound type. As you can see in the example above, compound types are
used in the same way as fundamental types: the same syntax is used to declare variables and to
initialize them.
2.7. C++ Comment

A comment is text that the compiler ignores but that is useful for programmers. Comments are
normally used to annotate code for future reference. The compiler treats them as white space. You
can use comments in testing to make certain lines of code inactive. A C++ comment is written in
one of the following ways:

The /* (slash, asterisk) characters, followed by any sequence of characters (including new
lines), followed by the */ characters. This syntax is the same as ANSI C.

The // (two slashes) characters, followed by any sequence of characters. A new line not
immediately preceded by a backslash terminates this form of comment. Therefore, it is
commonly called a single-line comment.
The comment characters (/*, */, and //) have no special meaning within a character constant,
string literal, or comment.

Example:

int main()
{
//declaring integer and character variables
int a; char ch;
a=10; ch=’b’;
/*Printing the
variables
*/
cout<<“The value of ch is ” <<ch<<endl;
cout<<“The value of a is ”<<a<<endl;
return 0;
}
Output:
The value of ch is b
The value of a is 10

Notice the use of ―endl at the end of the cout statements. It simply adds a carriage return
which ends the current line.
2.8. Inputting Multiple Values

If you have multiple format specifiers within the string argument of cin, you can input multiple values.
All you need to do is to separate each format specifier with a ―>>‖a string that separates variables..
As a default, cin stops reading in a value when space, tab or Enter is pressed. Consider

cin>>roll_number>>MyAge;
(Assume that roll_number and MyAge have been declared beforehand!). If I entered: 1 2 and
pressed Enter, 1 would get assigned to roll_number, and 2 would get assigned to MyAge. But if I
entered 1, 2 and pressed Enter, roll_number would equal 1, but MyAge won't get assigned 2
because cin was not expecting a comma in the input string.

Now let us look at a way to get input from the user and store it in variables. Consider the following
program:

Example:

int main()

{
int a,b;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;

cout<< “The value of a is: ”<< a <<endl;

cout<<“The value of b is: ”<< b <<endl;

cout<< “Enter new value for both separated by a space: \n”; cin>>a >> b;

cout<< “New values are: ”<< a << “ ”<< b <<endl;

return 0;

}
Output:

Enter value of a:
4
Enter value of b:
7
The value of a is: 4
The value of b is: 7
Enter new value for both separated by a space:
25
New values are: 2 5

2.9. Arithmetic Operators

Arithmetic operators are commonly used in a variety of programming languages. In C, there are
five of them, and they all take two OPERANDS. Recall that an operand is an expression that is
required for an operator to work. For example, for 8 + 4, 8 and 4 are considered as the operands.

Operator Name Symbol


Multiplication *
Division /
Modulus %
Addition +
Subtraction -

2.9.1. What's With the % ?

Multiplication, addition and subtraction are the simplest to use. Division is also easy, but watch
out for the truncation of an int divided by an int! Now, the one that confuses novices is the modulus
operator, sometimes known as the remainder operator.
To keep things simple, a%b returns the REMAINDER that occurs after performing a/b. For this
operator, a andb MUST be integers!
For example, 6%3 returns 0 because 3goes into 6 EXACTLY. Similarly, 4%4, 8%2 and 16%8 all
return 0. So why does 3%4 return 3? Picture it this way: you have 3 holes to fill, but you can only fill
4 holes at a time. You can't fill a group of 4 holes, therefore the 3 holes you had are still empty. Similar
story for 7%4 because you can fill in one group of 4 but still have 3 holes remaining
Example:

int main()
{
Int a,b;
int sum;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;
sum=a+b;
cout<<“Sum: ”<<sum<<endl;
return 0;
}

Output:
Enter value of a:
3
Enter value of b:
6
Sum: 9

2.10. Practice Problem 1:

Calculate area and perimeter of rectangle.

Example:

/* C++ Program - Calculate Area and Perimeter of Rectangle */

#include<iostream>
using namespace std;
int main()
{
int len, bre, peri, area;
cout<<"Enter length and breadth of the rectangle:";
cin>>len>>bre;
area=len*bre;
peri=(2*len)+(2*bre);
cout<<"Area = "<<area<<"\tPerimeter="<<peri;
}
2.11. Practice Problem 2:
Fahrenheit to Centigrade Conversion.

Code:

/* C++ Program - Fahrenheit to Centigrade Conversion */

#include<iostream>

using namespace std;


int main()
{
float fah, cel;

cout<<"Enter temperature in Fahrenheit : ";

cin>>fah;

cel=(fah-32) / 1.8;

cout<<"Temperature in Celsius = "<<cel;

}
2.12. Practice Problem 3:

C++ Program - Addition, Subtraction, Multiplication, Division.

Code:
/* C++ Program - Addition, Subtraction, Multiplication, Division */
#include<iostream>
using namespace std;
int main()
{
int a, b, res;
cout<<"Enter two number :";
cin>>a>>b;
res=a+b;
cout<<"\nAddition = "<<res;
res=a-b;

cout<<"\nSubtraction = "<<res;

res=a*b;

cout<<"\nMultiplication = "<<res;

res=a/b;

cout<<"\nDivision = "<<res;

}
LAB TASKS
TASK NO. 1:
Write a program to assign float value, integer value and your name to the variables using
different variables while declaration. Then, print the assigned values on the screen.

TASK NO. 2:
Write a program to evaluate the given arithmetic expression and outputs its result on screen by
using the following steps.

(a-(b*c))+d

1. Assign a value 4 to the variable named a by using the desired variable type

2. Assign a value 3 to the variable named b by using the desired variable type

3. Assign a value 5 to the variable named c by using the desired variable type

4. Assign a value 2.5 to the variable named d by using the desired variable type

5. Save the output result in variable named result and display it on screen

TASK NO. 3:
Write a program to perform the following arithmetic operations and print their results on screen.

Use: a=5, b=2, c=1 by taking these values from user using “cin” command.

Find: add a and b, subtract a and c, product of b and c, divide a and c, remainder of c and a.

Print the results of all the mentioned operations on screen.

TASK NO. 4:
Write a Cpp program to calculate and outputs the circumference of a circle (C=2Пr, П=3.14)
using the define directive for assigning a constant value.

TASK NO. 5:
Write a program to read the name of a student and marks obtained in three subjects. Calculate total
and average. Each subject has a maximum of 100 marks.
Lab 3-Control Structure (Selection/Decision Structure)

Objective
By the end of this lab students will be able to:

• Become familiar with the types of control structures.


• Learn and understand the sequence structure and types of selection/decision structures.
• Learn the process of implementing various types of selection/decision structures.
• Understand how to use equality, relational, and logical operators as well as Boolean expressions in
selection/decision structures.
• Learn how to use compound statements and ternary conditional operator in C++.
• Understand the difference between assignment ‘=’ and equality operator ‘==’ in C++.
• Learn how to implement nested if/else structures.

In-Lab and In-Lab Tasks

Control structure
A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate,
repeat code or take decisions. Bohm and Jacopino’s work demonstrate that all programs could be written in
terms of only three control structures.
• Sequence structure
Built into C++. Programs executed sequentially by default.
• Selection structures
C++ has three types:
1. If
▪ Allows the program to make a decision or comparison and then select one of two paths,
depending on the result of the comparison.
▪ One statement or a block of statement enclosed in braces {} i.e. (compound statement), to be
processed If condition met otherwise it is skipped.

o Perform an action if condition is true.


o Skip the action if condition is false.
▪ Uses equality, Boolean, and relational operators.

▪ Conditions in if-structures can be formed using the equality, Boolean, and relational operators.

Equality operators

Same level of precedence

Associated left to right.


Relational operators

Same level of precedence.

Associated left to right.

Boolean Expressions
Boolean expressions are expressions that are either true or false.
(grade >= 60) Including the parentheses, is the boolean expression.

Equality operators precedence is lower then precedence of relational operators.

Standard algebraic C++ equality Example Meaning of


equality operator or or relational of C++ C++ condition
relational operator operator condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y

 >= x >= y x is greater than or equal to y

 <= x <= y x is less than or equal to y

Equality operators
= == x == y x is equal to y

 != x != y x is not equal to y

The primary C++ selection structure statement used to perform a single-alternative selection. If-structure choose
among alternative courses of action

▪ If the condition is true

o statement Print statement executed, program continues to next

▪ If the condition is false

o Print statement ignored, program continues

Syntax

▪ Pseudocode
If student’s grade is greater than or equal to 60

Print “Passed”

▪ C++ code
if ( grade >= 60 )
cout << "Passed";
EXAMPLE-1

▪ Following example used six if statements to compare two numbers input by the user.

▪ If the condition in any of these if statements is satisfied, the output statement associated with if
is executed.

▪ If the condition with the if statement is false the output statement associated with that if
statement is skipped.

▪ Observe the different outputs for various inputs at the end of the program.

2. if/else
▪ Perform an action if condition is true.
▪ Performs a different action if the condition is false.
Syntax

▪ A single statement for each alternative


if (Boolean_expression)
yes_statement;
else
no_statement;
▪ A sequence statement for each alternative

if (Boolean_expression)

{ yes_statement1;

yes_statement2;

yes_statement last; }

else

{ no_statement1;

no_statement2;

no_statement last; }

▪ Pseudocode

if student’s grade is greater than or equal to 60


print “Passed”
else
print “Failed”
▪ C++ code

if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
Compound Statement

▪ Set of statements within a pair of braces also known as BLOCK

if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
▪ Without braces,
cout << "You must take this course again.\n";
always executed
Example-2

Example-3
Program 1

Program 2

Example-4

Write a program to calculate the gross pay of an employee. The employee is paid at his basic hourly rate for
the first 40 hours worked during a week. Any hours worked beyond 40 is considered overtime. Overtime is
paid at the 1.5 times the hourly rate.
Ternary conditional operator (?:)

▪ It is only ternary operator.


▪ It takes three operands together with conditional operator to form a conditional expression
o Three arguments (condition, value if true, value if false)
o Example: cout << ( grade >= 60 ? “Passed” : “Failed” );

▪ the value in the conditional can also be actions to execute for example
grade >= 60 ? cout << “Passed” : cout << “Failed” ;
2.1 Nested If-Else Structure
▪ if structure that rests entirely within another if structure, within either the if or the else clause
o One inside another, test for multiple cases
o Once condition met, other statements skipped
Nested If-Else Structure Example-5
Consider an example of a program segment that accepts a gender code and print gender according to that code.
▪ Pseudocode
if the gender code is F
print female
else
if the gender code is M
print male
else
print invalid code

Nested If-Else Structure Example-6


▪ Pseudocode
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
▪ C++ code
if ( grade >= 90 ) // 90 and above
cout << "A";
else
if ( grade >= 80 ) // 80-89
cout << "B";
else
if ( grade >= 70 ) // 70-79
cout << "C";
else
if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
if grade>=90, first four conditions will be true. But only the cout statement after the first test will be
executed. After that cout is executed, the else part of the outer if/else statement is skipped.
Logical Operators
▪ Logical operators are used to combine more than one condition forming a complex condition.
▪ Allow you to combine two or more conditions into one compound condition
▪ Data validation
o the process of verifying that the input data is within the expected range
▪ C++ logical operators are:
a) && (Logical AND)
o All of the conditions must be true for the compound condition to be true
o Syntax (Condition_1) && (Condition_2)
o True if both expressions are true
o Example
if ( (2 < x) && (x < 7) )
True only if x is between 2 and 7
Inside parentheses are optional but enhance meaning
o Be careful translating inequalities to C++
o if x < y < z translates as
if ( ( x < y ) && ( y < z ) )
NOT
if ( x < y < z )
b) || (Logical OR)
o only one of the conditions must be true for the compound condition to be true
o True if either or both expressions are true
o Syntax (Condition_1) || (Condition_2)
o Example
if ( ( x = = 1) | | ( x = = y) )
True if x contains 1
True if x contains the same value as y
True if both comparisons are true
c) ! (Logical NOT , logical negation)
o Reverses the truth/falsity of its condition
o Returns true when its condition is false, & vice versa
o Is a unary operator, only takes one condition
o Example
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
ALTERNATIVE
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
o ! negates any boolean expression
o !( x < y)
True if x is NOT less than y
o !(x = = y)
True if x is NOT equal to y
o ! Operator can make expressions difficult to understand…use only when appropriate

Example-6

Confusing Equality (==) and Assignment (=) Operators Common error

▪ Does not typically cause syntax errors


▪ = Assignment operator
Used to assign values to variables
X=3
▪ == equality operator
Used to compare values
If (X == 3)
3. switch
▪ Perform one of many different actions depending on the value of an integer expression.
• Repetition structures
▪ Many application require certain operations to be carried out more than once. Such situations
require repetition in control flow.
C++ has three types:
1. While
▪ An action to be repeated while some conditions remains true.
2. Do/while
▪ Similar to while structure.
▪ Tests the loop continuation after the loop body is performed.
3. For
▪ Repeat statement while condition remains true.
▪ Specifies initialization and incremental instructions.

Post-Lab Tasks
TASK 1: Autonomous Car Traffic Light Decision

An autonomous car must decide whether to continue driving or stop based on the traffic light color. Write a
C++ program that:

• Takes the traffic light color as input (a string: "green", "yellow", or "red").
• Uses an if-else statement to:
o Print "Continue driving" if the light is "green".
o Print "Stop" if the light is "yellow" or "red".

TASK 2: Robot Door Check


A robot needs to determine if it can proceed based on whether a door is open or closed. Write a C++ program
that:

• Takes the door status as input (a boolean: 1 for open, 0 for closed).
• Uses an if-else statement to:
o Print "Proceed" if the door is open (1).
o Print "Wait" if the door is closed (0).

TASK 3: Space Mission Launch Conditions

A spacecraft can launch only if multiple conditions are satisfied: the weather must be clear, the fuel level must
be sufficient, and all systems must be operational. Write a C++ program that:

• Takes three inputs:


o Weather status (string: "clear" or "not clear").
o Fuel level (integer: 0 to 100).
o System status (string: "operational" or "failure").

Uses nested if-else statements to:

• Check if the weather is "clear".


o If true, check if the fuel level is at least 80.
▪ If true, check if the system status is "operational".
• Print "Launch" if all conditions are met.
• Otherwise, print the first condition that fails: "Weather not clear", "Insufficient fuel", or "System
failure".

TASK 4: Robot Maze Navigation

A robot navigating a maze must decide its next move based on obstacles ahead and to the left. Write a C++
program that:

• Takes two inputs:


o Obstacle in front (boolean: 1 for yes, 0 for no).
o Obstacle on the left (boolean: 1 for yes, 0 for no).
• Uses nested if-else statements to:
o Check if there is no obstacle in front (0), then print "Move forward".
o If there is an obstacle in front (1):
▪ Check if there is no obstacle on the left (0), then print "Turn left".

TASK 5: Password Mismatch Error Messages

A login system displays specific error messages based on the type of password mismatch. Write a C++ program
that:

• Takes the mismatch type as input (integer: 1 for incorrect username, 2 for incorrect password, 3 for both
incorrect).
• Uses a switch statement to print:
o "Incorrect username" for 1.
o "Incorrect password" for 2.
o "Both username and password incorrect" for 3.
o "Unknown error" for any other input.
Lab 4- Control Structure (Repetition Structure)

Objective
By the end of this lab students will be able to:

• Learn and understand different types of repetition structures.


• Learn the process of implementing various repetition structures in C++.
• Learn how to use and implement break and continue statements in repetition structures.

In-Lab and In-Lab Tasks

• While repetition structure:


Action repeated while some condition remains true. When an action must be repeated, a loop is
used.

Syntax:

 First, the condition is evaluated


◼ If true, the body of the loop is executed and the control is transferred back to the condition for re-
evaluation
 During execution, some item from the boolean expression is changed
◼ If false, the while loop is exited and control is transferred to the statement after the while loop
body.
◼ A while loop might not execute at all if the boolean expression is false on the first check.
Example:
Program to print greetings “Hello!” for a number of times user want to print.
//a while loop example
//program to print the hello greetings
//user give the number of times hello greeting to be printed.
#include <iostream>
using namespace std;
int main()
{
int count_down; //declaring count_down as an integer variable
cout << "How many greetings do u want\n"; //prompt user to enter the number for
greetings
cin >> count_down; //reading value this value gives number of times
greeting will appears

while (count_down > 0) //while loop condition, if countdown is greater than zero
{
cout << "HELLO!\t"; //printing hello
count_down = count_down - 1; //decrementing the value in count_down (counter) by
1
} //while body ends here
cout << endl;
cout << "thats all \n" << "have a great day";
return 0;
}
Example:
Print 1 to 100 using a while loop.
#include <iostream>
using namespace std;
int main()
{
int count; //declaration of control variable count
count = 1; //initialization of control variable
while (count <= 100) //while count is less than 100 program will print the count
{
cout << count << "\t";
count = count + 1; //add one to the count every time the loop repeats.
} /*when count is greater than 100 then the loop will
terminate and the statement next to the while loop will execute*/
return 0; //indicated successful termination
} //end of function main
Example:
Take grades of class students from user and find the average grade of class using while loop.
// example
// Class average program with counter-controlled repetition.
#include <iostream>
using namespace std;
// function main begins program execution
int main()
{
int total; // sum of grades input by user
int gradeCounter; // number of grade to be entered next
int grade; // grade value
int average; // average of grades
// initialization phase
total = 0; // initialize total
gradeCounter = 1; // initialize loop counter
// processing phase
while (gradeCounter <= 10) { // loop 10 times
cout << "Enter grade: "; // prompt for input
cin >> grade; // read grade from user
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
}
// termination phase
average = total / 10; // integer division
// display result
cout << "Class average is " << average << endl;
return 0; // indicate program ended successfully
} // end function main

Sentinel Controlled Variable:


Sentinel variable tested in condition; loop ends when sentinel encountered.
Syntax
cin >> variable; //initialize loop control variable

while (variable != sentinel) //test loop control variable


{
.
.
cin >> variable; //update loop control variable
.
.
}

• Do-while repetition structure:


Variation of the while loop. A do-while loop is always executed at least once. Makes loop
continuation test at the end not the beginning. The body of the loop is first executed i.e. the condition (boolean
expression) is checked after the body has been executed.

Syntax:
do {
statement block
} while (condition)
OR
do {
statement block
} while (condition);
Example:
Print 1-10 using do-while loop.
#include <iostream> //preprocessor directive
using namespace std;
int main()
{
int counter = 1; //initializing counter to 1
do
{ //do while loop begins
cout << counter << " "; //display counter
} while (++counter <= 10);//loop continuation test
// do while loop ends
cout << endl;
return 0;
}

• For loop repetition structure:


for loop is used when the number of times to be repeated is fixed/known. It handles all the details
of the counter controlled repetition. Execution continues as long as the boolean expression is true.

Syntax:
for (initialization; Loop Continuation Test; update)
{
statement block;
}

Syntax comparison with while loop

initialization;
while ( loop Continuation Test)
{ statement
increment;}

◼ Initialization action
 Done only once at the start
 Initialization expression initialize and declare the loop’s control variable e.g. int counter
= 1;
 Notice that there is a semi colon after initialization statement
◼ Loop continuation test
 Is a boolean expression
 Expreassion contains the final value of the control variable for which the condition is true
e.g. counter <= 10;
 Loop continuation test evaluates to true or false
 If true body of for is executed, else exit for loop
 Notice that there is also a semi colon after loop condition test
◼ Update
 Specifies how to update condition
 After the execution of the body of the loop, the condition of the loop is updated e.g.
counter ++
 Notice that there is no semi colon after updat_action
Examples using for loop:
◼ Vary control variable from 1 to 100 in increments of 1
 for (int i = 1, i <= 100; i++)
◼ Vary control variable from 100 to 1 in decrements of -1
 for (int i = 100, i >= 1; i--)
◼ Vary control variable from 7 to 77 in steps of 7
 for (int i = 7, i <= 77; i += 7)
◼ Vary control variable from 20 to 2 in steps of -2
 for (int i = 20, i >= 2; i -= 2)
Example:
Print 1-10 using for loop.
#include <iostream>
using namespace std;
int main()
{
for (int counter = 1; counter <= 10; counter++)
cout << counter << endl;
return 0;
}
Example:
Add even integers from 2-100 using for loop.
#include <iostream>
using namespace std;
int main()
{
int sum = 0; // initialize sum
for (int number = 2; number <= 100; number += 2)
sum += number; // add number to sum
cout << "Sum is " << sum << endl; // output sum
return 0; // successful termination
} // end function main

Multiple variables in for loop:


There may be several variables in the for structure that must be initialized and updated (e.g.
incremented or decrement). Coma operator is used to enable the programmer to use multiple
initialization and increment expressions
For multiple variables, use comma-separated lists as:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;

• Continue and break statements and Nested Control Structures:


 The break and continue statements alter the flow of control
 break statement
◼ Causes immediate exit from while, for, do/while or switch structure
◼ Program execution continues with first statement after structure
◼ Example:
#include <iostream>
using namespace std;
int main()
{
int x;
for (x = 1; x <= 10; x++)
{ if (x == 5)
break; // break loop only if x is 5
cout<< x << " "; // display value of x
} // end for
cout << "\nBroke out of loop when x became " << x << endl;
return 0; // indicate successful termination
} // end function main

 continue statement
◼ Used in while, for, do/while
◼ Skips remainder of loop body
◼ Proceeds with next iteration of loop
In while and do/while structure
◼ Loop-continuation test evaluated immediately after the continue statement
for structure
◼ Increment expression executed
◼ Next, loop-continuation test evaluated
◼ Example:
#include <iostream>
using namespace std;
int main()
{
for (int x = 1; x <= 10; x++)
// if x is 5, continue with next iteration of loop
{ if (x == 5)
continue; // skip remaining code in loop body
cout << x << " "; // display value of x
} // end for structure
cout << "\nUsed continue to skip printing the value 5"<< endl;
return 0; // indicate successful termination
} // end function main

LAB TASKS
Task 1: Design a program that calculates the factorial of a number given as an input by the user by applying while loop.
Task 2: Apply while loop and for loop to design a C++ program in order to add odd numbers between 1 and 50.
Task 3: Write a program to add numbers entered by a user until the user enter zero using do-while loop.
Task 4: Write a C++ program to print a table of 2.
Lab 7 – Functions - I

Objective
By the end of this lab students will be able to:

 Learn and understand difference between pre-packaged functions and programmer-defined functions.
 Able to understand the function structure focusing on function prototype and function definition.
 Learn how to use and implement functions in C++.

In-Lab and In-Lab Tasks

 Modular programming with Functions:


Best way to construct a large program is to construct it from smaller pieces or components
(modules). Each piece/module is more manageable than the original program. Modules in c++ are
functions and classes.
o Function is a group of statements that is executed when it is called from some point of the
program. Functions allow the programmer to modularize a program, accessing all the potential
that structured programming can offer in C++. Function can be called multiple times in a program
o Advantages of modular programming:
Subtasks, or functions in C++, make programs
 Easier to understand, change, write, test, debug
 Easier for teams to develop
 C++ programs can be written by combining
Programmer defined functions
Pre- packaged functions
Are available in standard C++ library
Provided as part of the C++ programming environment
 C++ library provides rich collection of functions for performing common mathematical
calculations
String manipulations
Character manipulations
 Function Libraries:
Predefined functions are found in libraries. The library must be “included” in a program
to make the functions available. An include directive tells the compiler which
library header file to include.
o To include the math library containing sqrt():
#include <cmath>
o Newer standard libraries, such as cmath, also require the directive:
using namespace std;
o Math library functions
Allow the programmer to perform common mathematical calculations. Use math library
functions including the header file <cmath>
 Example:
cout << sqrt( 900.0 );
Calls the sqrt (square root) function. The preceding statement would print 30. The sqrt
function takes an argument of type double and returns a result of type double, as do all
functions in the math library.
 Function call arguments can be
Constants
sqrt( 4.0 );
Variables
sqrt( x );
Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3y + 6 );
 Commonly used math library functions
Method Description Example
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 )
point number is 1.992
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) 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 sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)

 Program example to observe predefined functions:


//program to find the square root of any number by calling a predefined math function for sq. root.
#include <iostream>
#include <cmath> //math library header file
using namespace std;
int main()
{ double x;
cout<<"enter a number to find its sqrt";
cin>>x;
cout<<sqrt(x);// calling predefined function for square root
return 0;
}
 Functions:
o Modularize a program
o Software reusability
 Call function multiple times
o Local variables
 Known only in the function in which they are defined
 All variables declared in function definitions are local variables
o Parameters
 Local variables passed to function when called
 Provide outside information
o Function call
 We already discussed the function call previously. We are discussing it again here for
revision purpose. Function is invoked by function call. A function call specifies the
function name and provides information (as arguments) that the called function needs.
Functions called by writing.
functionName (argument);
or
functionName(argument1, argument2, …);
The argument can be a constant, variable or expression.
o Function Definitions
Each program we observed so far consisted of a function called main. Function main called
standard library functions to accomplish its task. Now we are going to discuss how programmer
write their own customized functions. For programmer defined functions, the important
components are:
 Function definition
Describes how the function does its task. Can appear before or after the function is called.
Syntax:
return-value-type function-name( parameter-list )
{
declarations and statements
}
Function-name
is any valid identifier e.g. square.
Return-value-type
is the data type of the result returned from the function to the caller. Return value type void
indicated that the function does not return a value.
Parameter-list
is a comma-separated list of the arguments. Containing the declarations (data type needed for
each argument) of the parameters received by the function when it is called. If the function
does not receive any values, parameter-list is void or simply left empty.
Example function:
int square( int y )
{
return y * y;
}
return keyword
Syntax: return expression;
Returns the value calculated by the function. Returns data, and control goes to function’s
caller. If no data to return, use return; Function ends when reaches right brace and control
goes to caller.

Functions cannot be defined inside other functions

 Function prototype
Must appear in the code before the function can be called. The compiler use the function
prototypes to validate function call.
Syntax:
Return-value-type Function_Name(Parameter_List);
Function prototype tells the compiler the function’s name, type of data returned by the
function (void if return nothing), Number of parameters the function accepts to receive,
Types of parameters, The order in which these parameters are expected.
Function prototype is not required if the function definition appears before the function’s first use
in the program. In such case the function definition also acts as the function prototype
Example:
// program calculate the square of integers 1 to 10
// Creating and using a programmer-defined function.
#include <iostream>
using namespace std;
int square( int ); // function prototype
int main()
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
cout << endl;
return 0; // indicates successful termination
} // end main
// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
} // end function square

1 4 9 16 25 36 49 64 81 100

 Prototype must match function definition


Function prototype
double maximum( double, double, double );
Definition
double maximum( double x, double y, double z )
{

}
observe this in the following program example. This example program uses a programmer-defined function
maximum to determine and return the largest of three integers
 Example:
// using programmer defined function

// Finding the maximum of three floating-point numbers.


#include <iostream>
using namespace std;
double maximum( double, double, double ); // function prototype
int main()
{
double number1;
double number2;
double number3;
cout << "Enter three floating-point numbers:";
cin >> number1 >> number2 >> number3;
// number1, number2 and number3 are arguments to
// the maximum function call
cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl;
return 0; // indicates successful termination
} // end main
// function maximum definition;
// x, y and z are parameters
double maximum( double x, double y, double z )
{
double max = x; // assume x is largest
if ( y > max ) // if y is larger,
max = y; // assign y to max
if ( z > max ) // if z is larger,
max = z; // assign z to max
return max; // max is largest value
} // end function maximum

output

 Function signature
Function signature is also called simply signature. It is the portion of a function prototype that
includes name of function and parameters (types of its argument).
o Example:
double maximum( double, double, double );

Function signature

 Argument correction
Forcing the argument to the appropriate type. Argument values that do not correspond precisely to
the parameter types in the function prototype are converted to proper type before the function is
called.
o Example
sqrt a math library function has prototype in <cmath> that specifies a double argument.
sqrt can be called with an integer argument, the function will still work correctly.
Statement cout << sqrt(4) correctly evaluate and prints 2
Function prototype causes compiler to convert int value 4 to the double value 4.0 before
the value is passed to sqrt. However changing from double to int can truncate data e.g. 3.5
to 3. Converting values to lower type can lead to incorrect result. As we saw some of the
conversions may lead to incorrect results if proper promotion rules are not followed.
o Promotion rules
The promotion rules specify how types can be converted to other types without losing data.
Promotion rules apply to expressions containing values of two or more data types (mixed-
type-expressions). Type of each value in a mixed-type expression is promoted to the
“highest” type in the expression. Also used when the type of an argument to a function
does not match the parameter type specified in the function definition.
o Promotion hierarchy for built in data types
Data types
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool (false becomes 0, true becomes 1)

 Header Files
Library header file contain function prototypes for library functions. Definition of various data
type and constants needed by library functions <cstdlib> , <cmath>, etc. and Load with #include
<filename>.
o Example:
#include <cmath>
o Custom header files: Defined by the programmer and save as filename.h. Included in a
program using #include preprocessor directive as:
#include “filename.h”
 Example:
#include “square.h” //square.h is programmer defined header file. The programmer
defined header file should end with .h.

LAB TASKS
Task 1: Display the following pattern

Task 2: Write a program to pass two numbers to the function body and print the greater number on the screen.
Task 3: Develop a C++ program to pass a number as argument to the function body. Print the table of that number in
function body.
Lab 8 – Functions - II

Objective
By the end of this lab students will be able to:

 Learn and understand difference between local variables, global constants, and global variables.
 Able to differentiate various storage class specifiers.
 Learn and understand scope rules in functions.

In-Lab and In-Lab Tasks

Local Variables
 Variables declared in a function are local to that function; they cannot be used from outside the function.
They have the function as their scope.
 Variables declared in the main part of a program; are local to the main part of the program, they cannot
be used from outside the main part. They have the main part as their scope.
 Example:
#include<iostream>
using namespace std;
int sum (int, int);
int main()
{
int a=10, b=100, s;
s=sum(a,b);
cout<<"sum is"<<s;
return 0;
}
int sum (int x, int y)
{
int rs;
rs=x+y;
return rs;
}
Variables a, b, s are local variables for main function whereas the variables x, y, rs are local variables for
“sum” function. When the function “sum” is called, the control is transferred to the function definition
“sum”. Then, the variables x, y, rs are created in memory and the values 10 is stored in variable “x”
whereas 100 is stored in “y” variable. The sum of “x” and “y” is calculated inside the function definition
and the result is returned to the calling function. When the control returns the variables x, y, and rs are
destroyed from the memory.

Global Constants
 Global Named Constant available to more than one function as well as the main part of the program as
they are declared outside any function body and the main function body. They can be declared before any
function that uses it.
 Example:
const double PI = 3.14159;
double volume(double);
int main()
{…}
PI is available to both the main function and to function volume.

Global Variables
 Rarely used when more than one function must use a common variable. These are declared just like a
global constant except const is not used. Generally make programs more difficult to
understand and maintain.
 Example:
#include<iostream>
using namespace std;
int a, b, s;
int sum (int, int);
int main()
{
a=10;
b=100 ;
s=sum(a,b);
cout<<"sum is"<<s;
return 0;
}
int sum (int x, int y)
{
int rs;
rs=x+y;
return rs;
}
Storage Classes
Attributes of variable includes name, type, size and value. Each identifier in a program also has other attributes
including:

 Storage class: How long variable exists in memory


 Scope: Where variable can be referenced in program
 Linkage: For multiple source-file program, which files can use it

C++ provides five storage class specifiers. An identifier’s storage class specifier helps determine its Storage
class, scope and linkage

 Auto

 Register

 Extern

 Mutable

 Static

The storage class specifiers can be split into two storage classes

 Automatic storage class


 Static storage class

Automatic Storage Classes


Key words auto and register are used to declare variables of automatic storage class. Variable created when
program enters its block. Variable exist while the block is active and variable destroyed when program leaves
block.

 auto keyword: Only local variables of functions can be automatic and are automatic by default.
keyword auto explicitly declares automatic.
Example
auto double x, y; /*indicates x and y are local variables of automatic storage class, exist only in the
body of function in which definition appear*/.
 register keyword: Hint to place variable in high-speed register and is good for often-used items (loop
counters). It’s often unnecessary, compiler optimizes.
Example
register int counter = 1; /*integer variable counter be placed in one of the computer’s registers, counter
is initialized to 1*/.

Specify either register or auto, not both


Static storage class
Keywords extern and static are used to declare identifiers for variables and functions of static storage class.
Variables exist for entire program and for functions, name exists for entire program. May not be accessible, scope
rules still apply (more later).

 static keyword: Local variables in function declared with keyword static. Keeps value between function
calls and are only known in own function. Static local variables retain their values when function is exited.
Example
#include<iostream>
using namespace std;
int temp (int);
int main()
{
int i;
for (i=1; i<=3;i++)
{cout<<temp(i)<<endl;}
return 0;
}
int temp (int x)
{
static int co=10; //to get last updated value multiplied by upcoming value
co=co*x;
return co;
}

 extern keyword: External identifier and by default are for global variables/functions names where global
variable declaration takes place outside of a function block. Known in any function that comes after it.
Global variables retain value through out the execution of program. Generally the use of global variable
should be avoided except in certain situations with unique performance requirement

Scope Rules
Portion of program where identifier can be used. Scopes for an identifier are:
 Function scope
 File scope
 Block scope
 Function prototype scope
 Class scope (discuss later)
 namespace scope (discuss later)

File scope
Defined outside a function and is known in all functions. Global variables, function definitions and prototypes
all have file scope.
Function scope
Can only be referenced inside function in which they appear, can not be referenced outside function body. Only
labels are the identifiers with function scope and labels are identifiers with a colon e.g. case: (as used in switch).

Block scope
Identifiers declared inside the block and begins at declaration, ends at right brace } of the block i.e. it can only be
referenced in this range. In case of nested blocks and identifiers in inner and outer block have same name.
Identifier in the outer block is hidden until the inner block terminates.

static variables still have block scope and storage duration does not effect the scope of block.

Function-prototype scope
Only identifiers with this scope are those used in Parameter list of prototype. Names in function prototype
optional, only type required. Compiler ignores the name if used in parameter list of function-prototype

In a single prototype, name can be used once. Identifier used in function prototype can be reused elsewhere in the
program.

Example

Now, we are going to discuss a program that will demonstrates the scoping issues with

 Global variables
 Automatic local variables
 Static local variables
Program description
Global variable x is declared and initialized to 1, hidden in any block or function with a variable named x declared
in it.

In main local variable x is declared and initialized to 5 and printed to show that global x is hidden in main. x=5
is printed to show that global x is hidden in main.

New block defined in main with local variable x initialized to 7, printed to show it hides x in outer block of main,
x=7 automatically destroyed when block is exited. Printed to show it hides x in outer block of main.

Three functions useLocal, useStaticLocal and useGlobal are defined. Functions take no argument and return
nothing.

 Function useLocal defines automatic variable x = 25. calling useLocal prints x, increment and then again
print x. Each time function is called auto variable is recreated and initialized to 25.
 UseStaticLocal declare static variable x = 50 local variable declared static retain their value even when
out of scope. calling UseStaticLocal prints x, increment and then again print x.
 useGlobal does not declare any variable so it uses the global x. Calling function prints global variable,
multiply it by 10, printed again before exiting function. Next time it is called, global variable has its
modified value i.e. 10.
Finally the program prints the local variable x in main again to show; none of the function calls modified the
value of x because the function referred to variables in other scopes.

CODE
// A scoping example.

#include <iostream>

using std::cout;

using std::endl;

void useLocal( void ); // function prototype

void useStaticLocal( void ); // function prototype

void useGlobal( void ); // function prototype

int x = 1; // global variable

int main()

int x = 5; // local variable to main

cout << "local x in main's outer scope is " << x << endl;

{ // start new scope

int x = 7;

cout << "local x in main's inner scope is " << x << endl;

} // end new scope

cout << "local x in main's outer scope is " << x << endl;

useLocal(); // useLocal has local x

useStaticLocal(); // useStaticLocal has static local x

useGlobal(); // useGlobal uses global x

useLocal(); // useLocal reinitializes its local x

useStaticLocal(); // static local x retains its prior value

useGlobal(); // global x also retains its value

cout << "\nlocal x in main is " << x << endl;

return 0; // indicates successful termination

} // end main
// useLocal reinitializes local variable x during each call

void useLocal( void )

int x = 25; // initialized each time useLocal is called

cout << endl << "local x is " << x << " on entering useLocal" << endl;

++x;

cout << "local x is " << x

<< " on exiting useLocal" << endl;

} // end function useLocal

// useStaticLocal initializes static local variable x only the

// first time the function is called; value of x is saved

// between calls to this function

void useStaticLocal( void )

// initialized only first time useStaticLocal is called

static int x = 50;

cout << endl << "local static x is " << x

<< " on entering useStaticLocal" << endl;

++x;

cout << "local static x is " << x << " on exiting useStaticLocal" << endl;

} // end function useStaticLocal

// useGlobal modifies global variable x during each call

void useGlobal( void )

cout << endl << "global x is " << x << " on entering useGlobal" << endl;

x *= 10;

cout << "global x is " << x << " on exiting useGlobal" << endl;

} // end function useGlobal


LAB TASKS
Task 1: Write a C++ program to determine if a number entered by user is prime or not by using a function.
Task 2: Develop a C++ program to pass an integer as an argument to a function so that the function returns an integer with
its digits in a reverse order e.g. your function takes 1234 value as an input and returns it as 4321.
Task 3: Write a C++ program to find the exponential power of a given number by a function.
Lab 9 – Arrays

Objective
By the end of this lab students will be able to:
 Learn and understand arrays.
 Able to use arrays with repetition structure and functions.
 Understand various functions in arrays e.g. sorting, searching etc.
 Understand and able to implement multiple subscripted arrays.

In-Lab and In-Lab Tasks

Arrays:
Arrays are data structures consisting of related data items of the same type. An array is used to process a collection of data
of the same type. For example: list of names, list of temperatures etc. Arrays are:
 are static entities (same size throughout program)
 Consecutive group of memory locations
 Same name and type (int, char, etc.)

Array Variables:
The variables making up the array are referred to as Indexed variables, Subscripted variables, Elements of the array. The
number of indexed variables in an array is the declared size, or size of the array. The largest index is one less than the size.
The first index value is zero.

Declaring an Array
When declaring arrays, programmer specify Name, Type of array (Any data type), Number of elements (array size)
 Format
type arrayName[ arraySize ];
 Example
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
 Declaring multiple arrays of same type by use of comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
Array Variable Types
An array can have indexed variables of any type. All indexed variables in an array are of the same type that is the base
type of the array. An indexed variable can be used anywhere an ordinary variable of the base type is used.

Using [ ] With Arrays


In an array declaration, [ ]'s enclose the size of the array such as this array of 5 integers:
int score [5];
When referring to one of the indexed variables, the [ ]'s enclose a number identifying one of the indexed variables. E.g.
score[3] is one of the indexed variables. The value in the [ ]'s can be any expression that
evaluates to one of the integers 0 to (size -1)

Array
To refer to a particular location or an element in array, specify array name and position number (index).
 Format
arrayname[ position number ]
First element in every array is zeroth element . Consider N-element array c, so the elements are c[ 0 ], c[ 1 ] … c[ n - 1 ]
where Nth element as position N-1.
 Subscript is the position number within square brackets and must be an integer or an integer expression
(any integral type).
Name of array (Note
that all elements of
this array have the

c[0] -45
c[1] 6

A 12-element c[2]
c[3] 72
0

Array named c c[4]


c[5]
1543
-89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
Position number of the
element within array c
 Array elements assignment are like other variables assignment, printing for an integer array c:
c[ 0 ] = 3;
cout << c[ 0 ];
 Performing division on array element be like:
x = c[ 6 ] / 2; /*divide seventh element of array by 2 and assign the result to the variable x */
 printing sum of first three array elements of array c be:
cout << c[ 0 ] + c[ 1 ] + c[ 2 ];
 can perform operations inside subscript:
c[ 5 – 2 ] same as c[3]

Loops And Arrays


 For loop
For-loops are commonly used to step through arrays. Set each element; For example:
for (i = 0; i < 5; i++)
{
cout << score[i] << " off by "
<< (max - score[i]) << endl;
}
could display the difference between each score and the maximum score stored in an array

Initializing Arrays
If too few values are listed in an initialization statement. The listed values are used to initialize the first of
the indexed variables. The remaining indexed variables are initialized to a zero of the base type. For example:
int a[10] = {5, 5};
initializes a[0] and a[1] to 5 and
a[2] through a[9] to 0
Noe, If values listed in initialization statement are more than array elements, it causes a syntax error. Furthermore, to set
every element to same value:
int n[ 5 ] = { 0 };
 If array size omitted, values listed in initialization statement determine size
int n[] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
Example
Initializing the elements of an array to zeroes. Following program uses for repetition structure to initialize the elements of
a ten-element integer array n to zero and prints the array in a tabular form.
#include <iostream>
using namespace std;
#include <iomanip>
int main()
{
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
n[ i ] = 0; // set element at location i to 0
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
return 0; // indicates successful termination
} // end main
Example
Initializing the elements of an array with declaration. Following program initializes an integer array with 10 values and
prints the array in tabular format.
// Initializing an array with a declaration.
#include <iostream>
using namespace std;
#include <iomanip>
int main()
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int i = 0; i < 10; i++ )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
return 0; // indicates successful termination
} // end main
Array size (constant variables)
Array size can be specified with constant variable (const) as:
const int size = 20;
Also called named constants or read-only variables. Use constants to declare the size of an array as using a constant allows
your code to be easily altered for use on a smaller or larger set of data. For example:

//Constants must be initialized when declared and can not be modified there after
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];

for ( i = 0; i < NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by “
<< (max – score[i]) << endl;
Only the value of the constant can be changed to make this code work for any number of students.

Example
Generating values to be placed into an element of array. Following example initializes a 10-element array s to the integers
2,4,6,…..20 and prints the array in tabular format. These numbers are generated by multiplying each successive value of
the loop counter by 2 and adding 2.

// Initialize array s to the even integers from 2 to 20.


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// constant variable can be used to specify array size
const int arraySize = 10;
int s[ arraySize ]; // array s has 10 elements
for ( int i = 0; i < arraySize; i++ ) // set the values
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
return 0; // indicates successful termination
} // end main

Example
Computing the sum of the elements of an array. Following program sums the values contained in a the 12-element integer
array a.
// Compute the sum of the elements of the array.
#include <iostream>
using namespace std;
int main() {
const int arraySize = 10;
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
// sum contents of array a
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];
cout << "Total of array element values is " << total << endl;
return 0; // indicates successful termination
} // end main
Passing Arrays to functions
To pass an array to a function, specify the name of Array without brackets. For Example:
int myArray[ 24 ];
myFunction( myArray, 24 );
Pass array myArray to function myFunction. Array size is usually passed as it is useful to iterate over all elements. C++
automatically passes arrays to functions using simulated call-by-reference.
Arrays are passed by call-by-reference and functions can modify original array data. Value of name of array is address of
first element of array. Function knows where the array is stored and can modify the actual array elements in their original
memory locations.
Individual array elements passed by call-by-value just like regular simple variables. Such simple pieces of data are called
scalar or scalar quantities:
square( myArray[3] );
 Indexed variables can be arguments to functions. For example, if a program contains these declarations:
int i, n, a[10];
void my_function(int n);
Variables a[0] through a[9] are of type int, making these calls legal as:
my_function( a[ 0 ] );
my_function( a[ 3 ] );
my_function( a[ i ] );
Functions taking arrays for a function receiving array through function call, the function’s parameter list must specify that
an array will be received: like function prototype as:
void modifyArray( int b[], int arraySize );

and this prototype can also be written as:


void modifyArray(int anyArrayName[], int anyVariableName);

An array parameter is indicated using empty brackets in the parameter list. For example:
void fill_up(int a[ ], int size);
There is no need for array size between brackets as ignored by compiler;

Example of Function Calls With Arrays


If function fill_up is declared in this way:
void fill_up(int a[ ], int size);
and array score is declared this way:
int score[5], number_of_scores;
fill_up is called in this way:
fill_up( score, number_of_scores );

Example
Passing arrays and individual array elements to functions. Following program demonstrates the difference between passing
an entire array and passing an array element.
// Passing arrays and individual array elements to functions.
#include <iostream>
using namespace std;
#include <iomanip>
void modifyArray( int [], int ); // appears strange
void modifyElement( int );
int main()
{
const int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a
cout << "Effects of passing entire array by reference:"<< "\n\nThe values of the original array are:\n";
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 3 ) << a[ i ];
cout << endl;
// pass array a to modifyArray by reference
modifyArray( a, arraySize );
cout << "The values of the modified array are:\n";
// output modified array
for ( int j = 0; j < arraySize; j++ )
cout << setw( 3 ) << a[ j ];
// output value of a[ 3 ]
cout << "\n\n\n"<< "Effects of passing array element by value:" << "\n\nThe value of a[3] is " << a[ 3 ] << “\n'”;
// pass array element a[ 3 ] by value
modifyElement( a[ 3 ] );
// output value of a[ 3 ]
cout << "The value of a[3] is " << a[ 3 ] << endl;
return 0; // indicates successful termination
} // end main
// in function modifyArray, "b" points to
// the original array "a" in memory
void modifyArray( int b[], int sizeOfArray )
{
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;
} // end function modifyArray
// in function modifyElement, "e" is a local copy of
// array element a[ 3 ] passed from main
void modifyElement( int e )
{
// multiply parameter by 2
cout << "Value in modifyElement is "
<< ( e *= 2 ) << endl;
} // end function modifyElement
Output description
 Program first prints 5 elements of integer array a
 a and its size are passed to function modifyArray, where each of a’s elements is multiplied by 2
 a is reprinted in main
 Program prints the value of a[3] and passes it to function modifyElement
 Function modifyElement multiplies its argument by 2 and prints the new value
 Note that when a[3] is reprinted in main, it has not been modified, because individual array elements are
passed by call-by-value

Returning An Array
Recall that functions can return a value of type int, double, char, …, or a class type. Functions cannot return arrays. We
learn later how to return a pointer to an array

Sorting Arrays
Sorting data is an important computing application and virtually every organization must sort some data as massive amounts
of data required to be stored.
 Bubble sort (sinking sort)
Several passes through the array. Here, successive pairs of elements are compared. For example, if
increasing order (or identical), no change but if decreasing order, elements exchanged. Repeat these steps
for every element. For example:
Go left to right, and exchange elements as necessary with one pass for each element.
Original: 3 4 2 7 6
Pass 1: 3 2 4 6 7 (elements exchanged)
Pass 2: 2 3 4 6 7
Pass 3: 2 3 4 6 7 (no changes needed)
Pass 4: 2 3 4 6 7
Pass 5: 2 3 4 6 7
Small elements "bubble" to the top (like 2 in this example)
 Swapping variables
int x = 3, y = 4;
y = x;
x = y;

Example
Sorting an array with bubble sort. Following program sorts the values of a 10-element array into ascending order using the
bubble sort (sinking sort) technique as discussed earlier.

// This program sorts an array's values into ascending order.


#include <iostream>
using namespace std;
#include <iomanip>
int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements
cout << "Data items in original order\n";
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];
// bubble sort
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )
// loop to control number of comparisons per pass
for ( int j = 0; j < arraySize - 1; j++ )
// compare side-by-side elements and swap them if
// first element is greater than second element
if ( a[ j ] > a[ j + 1 ] ) {
hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = hold;
} // end if
cout << "\nData items in ascending order\n";
// output sorted array
for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];
cout << endl;
return 0; // indicates successful termination
} // end main

The chief virtue of bubble sort is that it is easy to program whereas the drawback is that it runs slowly, this becomes apparent
when sorting large arrays.

Computing Mean, Median and Mode Using Arrays


 Mean
 Arithmetic Average (sum/number of elements)
 Median
 Number in middle of sorted list
 1, 2, 3, 4, 5 (3 is median)
 If even number of elements, average of middle two number is median
 Mode
 Number that occurs most often
 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)

Example program
Survey data analysis program. The following program uses array response initialized with 99 responses to a survey. 99
responses are represented by constant variable responseSize. Each of the responses is a number from 1 to 9. Program
computes the mean.
// This program introduces the topic of survey data analysis.
// It computes the mean of the data.
#include <iostream>
using namespace std;
#include <iomanip>
void mean( const int [], int );
int main()
{
const int responseSize = 99; // size of array response
// initialize array responses
int response[ responseSize ] = { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,6, 7, 8, 9, 3, 9, 8, 7, 8, 7,7, 8, 9, 8, 9,
8, 9, 7, 8, 9,6, 7, 8, 7, 8, 7, 9, 8, 9, 2,7, 8, 9, 8, 9, 8, 9, 7, 5, 3,5, 6, 7, 2, 5, 3, 9, 4, 6, 4,7, 8, 9, 6, 8, 7, 8, 9, 7, 8,7, 4, 4, 2, 5,
3, 8, 7, 5, 6,4, 5, 6, 1, 6, 5, 7, 8, 7 };
// process responses
mean( response, responseSize );
return 0; // indicates successful termination
} // end main
// calculate average of all response values
void mean( const int answer[], int arraySize )
{
int total = 0;
cout << "********\n Mean\n********\n";
// total response values
for ( int i = 0; i < arraySize; i++ )
total += answer[ i ];
// format and output results
cout << "The mean is the average value of the data\n"<< "items. The mean is equal to the total of\n"<< "all the data
items divided by the number\n"<< "of data items (" << arraySize << "). The mean value for\nthis run is: " << total << " / "
<< arraySize << " = "<< static_cast< double >( total ) / arraySize << "\n\n";
} // end function mean
Searching Arrays
Often, programmer works with large amounts of data stored in arrays. Sometimes It is necessary to know, an Array contains
a value that matched a certain key value. Process of finding a particular element of array is called searching. Two searching
techniques are:
 Linear search technique
 Binary search technique
Linear Search
Compare each element of array with key value (search key). Here start at one end, go to other to know if search
key is present or not by examining every element. This works well for small and unsorted arrays and inefficient for
large arrays.

Example
Linear search of an array based example. Following program compares each element of array with the search key. Program
asks the user for the search key and user types the search key. Program compares it with each element of the array and then
specify the element number which is equal to the user’s search key

// Linear search of an array.


#include <iostream>
using namespace std;
int linearSearch( const int [], int, int ); // prototype
int main()
{
const int arraySize = 100; // size of array a
int a[ arraySize ]; // create array a
int searchKey; // value to locate in a
for ( int i = 0; i < arraySize; i++ ) // create some data
a[ i ] = 2 * i;
cout << "Enter integer search key: ";
cin >> searchKey;
// attempt to locate searchKey in array a
int element = linearSearch( a, searchKey, arraySize );
// display results
if ( element != -1 )
cout << "Found value in element " << element << endl;
else
cout << "Value not found" << endl;
return 0; // indicates successful termination
} // end main
// compare key to every element of array until location is
// found or until end of array is reached; return subscript of
// element if key or -1 if key not found
int linearSearch( const int array[], int key, int sizeOfArray )
{
for ( int j = 0; j < sizeOfArray; j++ )
if ( array[ j ] == key ) // if found,
return j; // return location of key

return -1; // key not found


} // end function linearSearch

Binary Search
Only used with sorted arrays. The process works as:
 Compare middle element with search key
 If equal, match found
 If key < middle element
Repeat search on first half of array
 If key > middle element
Repeat search on last half
 If search key is not middle element in specified sub array (piece of original array)
Algorithm is repeated on one quarter of original array
Binary search is Very fast
 At most N steps, where 2N > # of elements
 30 element array takes at most 5 steps
25 > 30

Example
Searching an array of 1024 elements will take 10 comparisons using binary search. Repeatedly dividing 1024 by 2 gives:
512, 256, 128, 64, 32, 16, 8, 4, 2, 1
1024 is divided by 2 only 10 times to get value 1
210 = 1024
After each comparison , half of array is eliminated. Following program performs the binary search of a sorted array. The
program is written in such a way that when it is executed, it asks the user for the search key and it shows all the elements of
the array in sorted form. Gives the result of the search. Also shows the iterations that were performed to find the element
that matches the search key.
// Binary search of an array.
#include <iostream>
#include <iomanip>
using namespace std;
// function prototypes
int binarySearch( const int [], int, int, int, int );
void printHeader( int );
void printRow( const int [], int, int, int, int );
int main()
{
const int arraySize = 15; // size of array a
int a[ arraySize ]; // create array a
int key; // value to locate in a
for ( int i = 0; i < arraySize; i++ ) // create some data
a[ i ] = 2 * i;
cout << "Enter a number between 0 and 28: ";
cin >> key;
printHeader( arraySize );
// search for key in array a
int result = binarySearch( a, key, 0, arraySize - 1, arraySize );
// display results
if ( result != -1 )
cout << '\n' << key << " found in array element "
<< result << endl;
else
cout << '\n' << key << " not found" << endl;

return 0; // indicates successful termination


} // end main
// function to perform binary search of an array
int binarySearch( const int b[], int searchKey, int low, int high, int size )
{
int middle;
// loop until low subscript is greater than high subscript
while ( low <= high ) {
// determine middle element of subarray being searched
middle = ( low + high ) / 2;
// display subarray used in this loop iteration
printRow( b, low, middle, high, size );
// if searchKey matches middle element, return middle
if ( searchKey == b[ middle ] ) // match
return middle;
else
// if searchKey less than middle element,
// set new high element
if ( searchKey < b[ middle ] )
high = middle - 1; // search low end of array

// if searchKey greater than middle element,


// set new low element
else
low = middle + 1; // search high end of array
}
return -1; // searchKey not found
} // end function binarySearch
// print header for output
void printHeader( int size )
{
cout << "\nSubscripts:\n";
// output column heads
for ( int j = 0; j < size; j++ )
cout << setw( 3 ) << j << ' ';
cout << '\n'; // start new line of output
// output line of - characters
for ( int k = 1; k <= 4 * size; k++ )
cout << '-';
cout << endl; // start new line of output
} // end function printHeader
// print one row of output showing the current
// part of the array being processed
void printRow( const int b[], int low, int mid,
int high, int size )
{
// loop through entire array
for ( int m = 0; m < size; m++ )
// display spaces if outside current subarray range
if ( m < low || m > high )
cout << " ";
// display middle element marked with a *
else
if ( m == mid ) // mark middle value
cout << setw( 3 ) << b[ m ] << '*';
// display other elements in subarray
else
cout << setw( 3 ) << b[ m ] << ' ';
cout << endl; // start new line of output
} // end function printRow
• Observe that maximum of 4 comparisons is required to
find the search key
• Array is 15 element, the first power of 2 greater than
15 is 4 which gives 16
• The middle element in each subscript array is marked
asterisk ( * ) to indicate the element with which the
search key is compared

Multiple-Subscripted Arrays
Arrays in c++ can have multiple subscripts. Its common use is to represent tables with rows and columns. Double-Subscript
arrays are used to identify a particular table element two subscripts must be specified:
a[ i ][ j ]
where a is the name of array, whereas i and j are the subscripts that uniquely identify each element. So specify row, then
column as:
(subscripts [i]=row & [j]=column)
Multiple subscript arrays can have more than two subscripts and C++ compilers support at least 12 array subscripts. For
example, a double subscript array with 3 rows and 4 columns is “Array of arrays”.
a[4] is an array of 4 elements
a[0][0] is the first element of array

Column 0 Column 1 Column 2 Column 3


Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript

Array name
Row subscript

Initializing Multiple-Subscripted Arrays


A multiple subscript array can be initialized in its declaration much like a single subscripted array.
 To initialize, initializers are grouped by row in braces:
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
 1 and 2 initialize b[0][0] and b[0][1] 1 2
 3 and 4 initialize b[1][0] and b[1][1] 3 4

 Default of 0, if not enough initializers for a given row, remaining elements are initialized to zero as:
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
1 0
These are referenced like normal as:
cout << b[ 0 ][ 1 ]; 3 4
This outputs 0 as 0 is element b[0][1] of array b. But it cannot reference using commas as:
cout << b[ 0, 1 ];

It gives syntax error.

Function prototypes
Must specify sizes of subscripts. First subscript not necessary, as with single-scripted arrays:
void printArray( int [][ 3 ] );
All subsequent subscript sizes are required. The compiler uses the sizes to determine locations of elements in memory.
Array elements are stored consecutively in memory regardless of number of subscripts. In double subscript array, first row
is stored in memory followed by the second row. Many common array manipulations use for repetition structures.
Example 1
for ( column=0; column <4; column++)
a[ 2 ][ column ];
Above statements sets all the elements in array a to zero. As we specified 3rd row so first subscript is always 2, for loop
varies only the second subscript (i.e., the column subscript). The above for structure is equivalent to the following
assignment statements:
a[ 2 ][ 0 ] = 0;
a[ 2 ][ 1 ] = 0;
a[ 2 ][ 2 ] = 0;
a[ 2 ][ 3 ] = 0;
Example 2
Following nested for structure determines the total of all the elements in array a:

total = 0;
for (row = 0; row < 3; row++)
for( column = 0; column < 4; column++)
total += a[ row ][ column ];
Here, for structure totals elements of array one row at a time. Outer for structure begins by setting row (subscript) to zero.
The inner for structure totals the elements of first row, outer for increment to 1 and so on. Result is printed when the nested
for structure terminates.

Example
Following program demonstrates initializing double-subscripted arrays in declarations. Program declares three arrays, each
with two rows and three columns.
 Declaration of array1 provides six initializers in two sublists
 Declaration of array2 provides five inializers in one sublist
 Declaration of array3 provides three initializers in two sublists
Remember each all three arrays are with two rows and three columns observe the effect of each declaration in the output.

// Initializing multidimensional arrays.


#include <iostream>
using namespace std;
void printArray( int [][ 3 ] );
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
cout << "Values in array1 by row are:" << endl;
printArray( array1 );
cout << "Values in array2 by row are:" << endl;
printArray( array2 );
cout << "Values in array3 by row are:" << endl;
printArray( array3 );
return 0; // indicates successful termination
} // end main
// function to output array with two rows and three columns
void printArray( int a[][ 3 ] )
{
for ( int i = 0; i < 2; i++ ) { // for each row

for ( int j = 0; j < 3; j++ ) // output column values


cout << a[ i ][ j ] ;
cout << endl; // start new line of output
} // end outer for structure
} // end function printArray

Notice the arrangement of elements in rows and columns


keeping in mind that
• Declaration of array1 provided six initializers in two sublists
• int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 }
};
• Declaration of array2 provided five inializers in one sublist
• int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
• Declaration of array3 provided three initializers in two
sublists
• int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
LAB TASKS
Task 1: write a program to find the maximum value in the array.
Task 2: write a program to input data into two different arrays and then to add the two arrays and store the result in a third
array.
Task 3: write a program to sort the mentioned below example by using bubble sorting method

4 19 1 13
.

Task 4: Write a program to keep track of students grades by a 3-by-4 array studentGrades is used (table), where each Row
of array represents a student and each column represent a grade on one of four exams. An example of that kind of table is
given below for 2-by-2 array.
…….
Quiz1 Quiz2

Student0 95 85
Student1 89 80
.
.

Array manipulation in program is performed by four functions


 Function minimum determines the lowest grade of any student for the semester
 Function maximum determines the lowest grade of any student for the semester
 Function average determines a particular student’s semester average
 Function printArray outputs the double-subscripted array in tabular form
Output
Task 5: Write a program that uses array response initialized with 99 responses to a survey. 99 responses are represented
by constant variable responseSize. Each of the responses is a number from 1 to 9. Program computes:
 The mean
 median and
 mode of the 99 values
Output
LAB: POINTERS - I

Objectives:

1. Introduction to Pointers
a. Declaring and Using Pointer Variables
b. Using the Indirection (Dereference) operator ‘*’
c. Using Address-Of Operator ‘&’
d. Pointers and Arrays

INTRODUCTION TO POINTERS

In the previous labs, we have not considered methods to control the amount of memory used in
a program. In particular, in all of the programs we have looked at so far, a certain amount of
memory is reserved for each declared variable at compilation time, and this memory is retained
for the variable as long as the program or block in which the variable is defined is active. In this
part of lab we introduce the notion of a pointer, which gives the programmer a greater level of
control over the way the program allocates and de-allocates memory during its execution.

DECLARING POINTERS

A pointer is just the memory address of a variable, so that a pointer variable is just a variable in
which we can store different memory addresses. Pointer variables are declared using a "*", and
have data types like the other variables we have seen. For example, the declaration

int *number_ptr; states that "number_ptr" is a pointer variable that can store addresses of
variables of data type "int".

For Example: int


rate = 100;

Then the variable ‘rate’ is stored at a specific memory address and as an illustration, can be
depicted as follows:
In the above example:

Address of variable “rate” = &rate = 1004

In programming we can find this address by “&” operator. This operator is called address
operator.

ADDRESS-OF OPERATOR ‘&’

Given a particular data type, such as "int", we can write assignment statements involving both
ordinary variables and pointer variables of this data type using the dereference operator "*" and
the (complementary) address-of operator "&". Roughly speaking, "*" means "the variable located
at the address", and "&" means "the address of the variable".

We can write a small code for saving the address of an integer:

int *ptr_rate; int rate=100; ptr_rate=&rate; // with this line


“ptr_rate” will be equal to 1004

POINTER OPERATIONS

Following are the operation of pointers

Pointer Operators
Operator Meaning
* Dereference (given a pointer, get the thing
referenced)
& Address of (given a thing, point to it)
EXAMPLE (POINTERS)

#include <iostream>
using namespace std; int
main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: "; cout <<
ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
}
OUTPUT

#include<iostream>
using namespace std;
void square(int *n);
int main() OUTPUT
EXAMPLE (POINTERS-II)

{ int v[3]={2,4,6};
for (int i=0;i<3;i++)
{
cout<<v[i]<<endl;
}
square(v); for (int i=0;i<3;i++)
{ cout<<v[i]<<endl;
} }
void square(int*n)
{
cout<<"**********"<<endl; for (int
i=0;i<3;i++)
{
cout<<n<<endl;
cout<<*n<<endl; *n= *n * *n;
cout<<n<<endl;
cout<<*n<<endl; n=n+1;
cout<<"**********"<<endl;
}
}

POINTERS AND ARRAYS

• Pointers are the variables that hold address. Not


only can pointers store address of a single
variable, it can also store address of cells of an array.

int* ptr; int arr[5]; ptr = &arr[2]; // &a[2] is the address of


third element of a[5].

• Suppose, pointer needs to point to the fourth element of an array, that is, hold address
of fourth array element in above case. Since ptr points to the third element in the above
example, ptr + 1 will point to the fourth element.
• You may think, ptr + 1 gives you the address of next byte to the ptr. But it's not correct.
• This is because pointer ptr is a pointer to an int and size of int is fixed for a operating
system (size of int is 4 byte of 64-bit operating system). Hence, the address between ptr
and ptr + 1 differs by 4 bytes.
• If pointer ptr was pointer to char then, the address between ptr and ptr + 1 would have
differed by 1 byte since size of a character is 1 byte.

EXAMPLE (POINTERS AND ARRAYS)

#include <iostream> OUTPUT


using namespace std; int main() {
float arr[5]; float *ptr;
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
} ptr = &arr[0];
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
}

LAB TASKS
LAB TASK NO 1: DEFINING POINTERS
Perform the following steps in a C++ program.
• Initialize num1, num2 and num3 with integers 3,4 and 6
• Initialize pointers variables ptr1, ptr2 and ptr3 to store address of num1, num2, and num3
respectively
• Perform following operations o *ptr1=*ptr2+*ptr3; o *ptr1++; o *ptr2--;
• Display output of num1, num2, num3 and addresses stored in the pointers ptr1, ptr2 and
ptr3 before and after the operations.
• Explain the difference in the outputs.
REQUIRED OUTPUT

LAB TASK NO 2: SWAPPING VARIABLES USING POINTERS


Write a C++ program that swaps values of two float type variables A and B. For swapping you can
use third variable temp to store values temporary. All accesses to the variables (A, B, and temp)
should be made through pointer notation only. In the end, print the values of variables (A, B) on
the screen. Note that during input and output the variables must be accessed through pointers
only.
REQUIRED OUTPUT

LAB TASK NO 3: ADD ARRAYS USING POINTERS


Suppose you have a main() with three local arrays, all the same size (5 elements) and type (float).
Initialize the first two arrays using pointers from the user. Write a function called addarrays() that
accepts the addresses of the three arrays as arguments; adds the contents of the first two arrays
together, element by element; and places the results in the third array. A fourth argument to this
function can carry the size of the arrays (if required). Use pointers only.
REQUIRED OUTPUT
Electrical Engineering Department

LAB -- STRUCTURES
Objectives:

1. Structures
• To become familiar with the concept of structures.
• To learn how structures are implemented.
• To learn how to implement structures with file I/O functions
2. Nested Structures

STRUCTURES
Structure is a collection of variables of different data types under a single name e.g., you want to
store some information about a person i.e., his/her name, citizenship number and salary. You can
easily create different variables “name”, “CitNo” and “salary” to store this information separately.

However, in the future, if you want to store information about multiple persons, you'd need to
create three different variables for each person i.e., name1, citNo1, salary1, name2, citNo2,
salary2 and so on. You can easily visualize how big and messy the code would look.

A better approach will be to have a collection of all related information under a single name
“Person”, and use it for every new person. Now, the code looks much cleaner, readable and
efficient as well.

This collection of all related information under a single name “Person” is called a structure.

To declare a structure in C++, the “struct” keyword is used to define a structure type followed by
an identifier (name of the structure). Then inside the curly braces, you can declare one or more
members (declare variables inside curly braces) of that structure. For example:

struct Person
{ char
name[50]; int
age; float
salary;
};

Here a structure “Person” is defined which has three members: name, age and salary. When a
structure is created, no memory is allocated. The structure definition is only the blueprint for the
creating of variables. You can imagine it as a datatype.
Electrical Engineering Department

The member of structure variable is accessed using a dot (.) operator. Suppose you want to access
“age” of structure variable “bill” and assign it 50 to it. You can perform this task as follows:

Person bill;
bill.age = 50;
You can also pass structure to a function in C++ programming. A structure variable can be passed
to a function in similar way as normal argument.

The following example is a C++ Program to assign data to members of a structure variable and
display it.

EXAMPLE
#include <iostream> using
namespace std; struct
part
{
int modelnumber;
int partnumber;
float cost;
}; void
main()
{
part part1;
part1.modelnumber=1234;
part1.partnumber=123;
part1.cost=100;
cout<<"Model: "<<part1.modelnumber<<endl;
cout<<"Part: "<<part1.partnumber<<endl; cout<<"Cost:
"<<part1.cost<<endl;
}
Electrical Engineering Department

Structure Definition:

LAB TASKS

LAB TASK NO 1: DEFINING STRUCTURES IN C++

Write a program in C++ that takes the record for 3 books of a student from the user. In each record
(for a single book), it should store “book id (int variable)”, “book title (character array or string
variable)”, “author (character array or string variable)” and its “price (float variable)”. The
program should take input for all the 3 books and store the data in an array of structure. In the
end, the program should display titles and price of only those books whose price is above 600.

LAB TASK NO 2: NESTED STRUCTURES IN C++

Consider the following nested structure with name employee. The structure has members:
“employeeID (int type)”, “employeeName (string type)”, “age (int type)”, “gender (char type)”, and
“salary (employeeSalary type)”. The “employeeSalary” structure contains three member
elements: “basicSalary (float type)”, “houseRent (float type)”, and “medical (float type)”. The
program should define an array of 3 employees in the “main( )” function. It is required to take
input for all the 3 employees from the user. The program should then display records of all those
employees having total salary greater than 50000.

LAB TASK NO 3: STRUCTURES WITH FILE I/O IN C++

Design a library management system using structure arrays. You are required to write a C++
program that collects data of all the available books using structures.

1) Name
Electrical Engineering Department

2) Volume
3) Edition
4) Author/s
5) Publisher

• The user will be asked to enter details of each case and once the details are stored in a
structure.
• The program should ask if you want to enter another data if YES then another set of details
will be entered, and the information will be appended in the file. If NO, then the program will
terminate.
• The program should also give an option to display the entries of the structures. So, write a
function that reads the contents of the stored data and displays all the entries on the screen.

Your overall program for this task should comprise of at least three functions: main(), readfile()
and writefile(). The purpose of these functions are as follows:

1) readfile() function reads the patient’s data and display it on the screen.
2) writefile() function takes patient’s data in form of a structure as argument and stores it at the
end of the structure.
3) The inputs from the user and display on console can be done in main() function.

The format in which data is to be written and read from the file is completely up to you.
Computer Programming Lab
Electrical Engineering Department

LAB - POINTERS-II
Objectives:

1. Operation on pointers
a. Incrementing a pointer
b. Decrementing a pointer
c. Comparing pointers
d. Addition/subtraction of a constant number to a pointer
e. Subtraction of one pointer from another
f. Operations not possible with pointers
2. The Null Pointer
3. Dynamic Memory Allocation
a. Using C++ operators ‘new’ and ‘delete’

OPERATION ON POINTERS

Pointers are variables that contain the memory address of another variable. Since an address in a
memory is a numeric value, we can perform arithmetic operations on the pointer values. The
different operations that can be possibly performed on pointers are as follows:

Incrementing a Pointer:
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer.
The following program increments the variable pointer to access each succeeding element of the
array.

EXAMPLE NO 1
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{ int var[MAX] = {10, 100, 200};
int *ptr;
ptr = var; // let us have array address in
pointer. for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
Computer Programming Lab
Electrical Engineering Department
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;

ptr++; // point to the next location


}
}

When the above code is compiled and executed, it produces result something as follows:

Output

Decrementing a Pointer:
The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below

EXAMPLE NO 2
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200}; int *ptr; ptr = &var[MAX-1]; // let us
have address of the last element in pointer.
for (int i = MAX; i > 0;
i--)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;

ptr--; // point to the previous location


}
}

When the above code is compiled and executed, it produces result something as follows.
Computer Programming Lab
Electrical Engineering Department

Output

Pointer Comparisons:
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point
to variables that are related to each other, such as elements of the same array, then p1 and p2
can be meaningfully compared.
The following program modifies the previous example one by incrementing the variable pointer
so long as the address to which it points is either less than or equal to the address of the last
element of the array, which is &var[MAX - 1]

EXAMPLE NO 3
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200}; int *ptr; ptr = var; //
let us have address of the first element in pointer.
int i = 0;
while ( ptr <= &var[MAX - 1] ) // pointer comparison
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
ptr++; // point to the next
location i++;
}
}

When the above code is compiled and executed, it produces result something as follows.
Computer Programming Lab
Electrical Engineering Department

Output

Addition/subtraction of a constant number to a pointer:


Addition or subtraction of a constant number to a pointer is allowed. The result is similar to the
increment or decrement operator with the only difference being the increase or decrease in the
memory location by the constant number given. Also, not to forget the values get incremented
or decremented according to the type of variable it stores. The following program shows an
example of addition and subtraction of a constant number to a pointer:

Note: – Output may vary every time the program is run because memory locations may differ with
each execution.

EXAMPLE NO 4
#include <iostream>
using namespace std;

void main()
{
int a=5,*x; //declaring the pointer for integer variable

x=&a; //storing the memory location of variable a in pointer variable x

/*The corresponding values of the addition and subtraction operations on pointer variable
x are given below*/
cout<<"x= "<<x<<endl; //printing the actual value of x
cout<<"x+3= "<<x+3<<endl; //the value incremented by 3
cout<<"x-2= "<<x-2<<endl; //the value decremented by 2

When the above code is compiled together and executed, it produces the following result.
Computer Programming Lab
Electrical Engineering Department

Output

Subtraction of one pointer from another:


A pointer variable can be subtracted from another pointer variable only if they point to the
elements of the same array. Also, subtraction of one pointer from another pointer that points to
the elements of the same array gives the number of elements between the array elements that
are indicated by the pointer. The following example shows this:

EXAMPLE NO 5
#include <iostream>
using namespace std;
void main() {
int num[10]={1,5,9,4,8,3,0,2,6,7};
int *a,*b;
a=&num[2]; //storing the address of num[2] in variable
a b=&num[6]; //storing the address of num[6] in variable
b

cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"a-b = "<<b-a<<endl;//prints the number of elements between the two elements
indicated by the pointers
cout<<"*a-*b = "<<*a-*b<<endl;//prints the difference in value of the two elements

When the above code is compiled together and executed, it produces the following result.

Output

Operations not possible with pointers:


Computer Programming Lab
Electrical Engineering Department

There are a few operations that are not possible with pointers. These are:

1. Addition of two pointer variables


2. Multiplication of a pointer with a constant value
3. Division of a pointer with a constant value

THE NULL POINTER

It is always a good practice to assign the pointer NULL to a pointer variable in case you do not
have exact address to be assigned. This is done at the time of variable declaration. A pointer that
is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries, including
iostream. Consider the following program.

#include <iostream>
using namespace std;

int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr <<endl;
}

When the above code is compiled and executed, it produces the following result.

Output

On most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0 has
special significance; it signals that the pointer is not intended to point to an accessible memory
location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to
nothing.

To check for a null pointer you can use an if statement as follows


Computer Programming Lab
Electrical Engineering Department
if(ptr) // succeeds if p is not null if(!ptr)
// succeeds if p is null

Note: Thus, if all unused pointers are given the null value and you avoid the use of a null pointer,
you can avoid the accidental misuse of an uninitialized pointer. Many times, uninitialized variables
hold some junk values and it becomes difficult to debug the program.

DYNAMIC MEMORY ALLOCATION

Dynamic memory allocation in C++ refers to performing memory allocation manually by


programmer.

What are applications?

• One use of dynamically allocated memory is to allocate memory of variable size which is
not possible with compiler allocated memory except variable length arrays.
• The most important use is flexibility provided to programmers. We are free to allocate and
deallocate memory whenever we need and whenever we don’t need anymore. There are
many cases where this flexibility helps. Examples of such cases are Linked List, Tree, etc.

How is it different from memory allocated to normal variables?


For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and
deallocated. For dynamically allocated memory like “int *p = new int”, it is programmers
responsibility to deallocate memory when no longer needed. If programmer doesn’t deallocate
memory, it causes memory leak (memory is not deallocated until program terminates).

How is memory allocated/deallocated in C++?


C++ has two operators “new” and “delete” that perform the task of allocating and freeing the
memory in a better and easier way.

NEW OPERATOR
Computer Programming Lab
Electrical Engineering Department

The new operator denotes a request for memory allocation. If sufficient memory is available, new
operator initializes the memory and returns the address of the newly allocated and initialized
memory to the pointer variable.

Syntax to use new operator: To allocate memory of any data type, the syntax is:

pointer-variable = new data-type;

Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type
including array or any user defined data types including structure and class.
int *p = NULL; // Pointer initialized with NULL p =
new int; // Then request memory for the variable

OR

int *p = new int; // Combine declaration of pointer and their assignment

Initialize memory: We can also initialize the memory using new operator:
pointer-variable = new data-
type(value);
Example:
int *p = new int(25); float
*q = new float(75.25);

Allocate block of memory: new operator is also used to allocate a block(an array) of memory of
type data-type. pointer-variable = new data-type[size]; where size (a variable) specifies the
number of elements in an array.

Example: int *p =
new int[10]

Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the
first element of the sequence, which is assigned to p (a pointer). P[0] refers to first element, P[1]
refers to second element and so on.
What if enough memory is not available during runtime?
If enough memory is not available to allocate, the new request indicates failure by throwing an
exception of type std::bad_alloc, unless “nothrow” is used with the new operator, in which case it
returns a NULL pointer. Therefore, it may be good idea to check for the pointer variable produced
by new before using it program.
Computer Programming Lab
Electrical Engineering Department

int *p = new(nothrow) int;


if (!p) {
cout << "Memory allocation failed";
}

DELETE OPERATOR

Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers


are provided delete operator by C++ language.

Syntax: delete pointer-variable; // Release memory pointed by pointer-variable

Here, pointer-variable is the pointer that points to the data object created by new.

To free the dynamically allocated array pointed by pointer-variable, use following form of delete:

delete[] pointer-variable; // Release block of memory pointed by pointer-variable

EXAMPLE NO 6
#include <iostream>
using namespace std;

int main ()
{
int* p = NULL; // Pointer initialization to null
p = new(nothrow) int; // Request memory for the variable using new operator
if (!p)
cout << "allocation of memory failed\n";
else
{
*p = 29; // Store value at allocated address
cout << "Value of p: " << *p << endl;
}
float *r = new float(75.25);
cout << "Value of r: " << *r << endl;
int n = 5;
int *q = new(nothrow) int[n]; // Request block of memory using new operator of size n
if
(!q)
cout << "allocation of memory failed\n";
else {
for (int i = 0; i < n; i++)
{
q[i] = i+1;
Computer Programming Lab
Electrical Engineering Department
}
cout << "Value store in block of memory: ";
for (int i = 0; i < n; i++)
{
cout << q[i] << " ";
}
cout<<endl;
}

// freed the allocated memory


delete p; delete r;

// freed the block of allocated memory


delete[] q;
}

Output
Computer Programming Lab
Electrical Engineering Department

LAB TASKS
LAB TASK NO 1: DYNAMIC MEMORY ALLOCATION
Write a C++ program that ask the user to enter Roll Numbers and GPAs of ‘N’ number of students
and display the entries on the screen. Where ‘N’ is the number of students entered by user in the
main function to allocate necessary memory dynamically. If the sufficient space is not available,
it exits after displaying an error message. Use exit(1) function to terminate the program.

Note: exit(0) behave like return 0 in main() function i.e., if program ended successfully. Whereas,
exit(non_zero_value) means the program was terminated with some kind of error.

If the sufficient space is available, then it reads the data from the dynamic array and display the
contents on the screen. Before exiting the program, the program deallocates the occupied space
using the delete operator, so that it becomes available for reuse.

Output
Computer Programming Lab
Electrical Engineering Department

LAB TASK NO 2: STRING REVERSAL USING POINTERS


Write a C++ program that can reverse a string i.e., character array using pointers. You need to take
a string in the form of a character array from the user in the main function and then pass the
pointer of the character array to a function ReverseString(). The function will reverse the array as
shown in the output.

Examples:
Input: Geeks
Output: skeeG

Approach: You can consider taking two pointers, one that points at the start of the string and the
other at the end of the string. The characters are then reversed one by one with the help of these
two pointers. You may use the built-in function ‘strlen(Input_String)’ to determine the length of
the string.

Output

You might also like