Project (1) - Compressed
Project (1) - Compressed
Flowcharts
Lab 1: Computer Programming
Flow Charts and Pseudo Codes
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:
Tasks:
2.1. Objectives:
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".
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.
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;
}
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:
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<< “Enter new value for both separated by a space: \n”; cin>>a >> b;
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
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.
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
Example:
#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:
#include<iostream>
cin>>fah;
cel=(fah-32) / 1.8;
}
2.12. Practice Problem 3:
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.
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:
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.
▪ Conditions in if-structures can be formed using the equality, Boolean, and relational operators.
Equality operators
Boolean Expressions
Boolean expressions are expressions that are either true or false.
(grade >= 60) Including the parentheses, is the boolean expression.
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
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
if (Boolean_expression)
{ yes_statement1;
yes_statement2;
yes_statement last; }
else
{ no_statement1;
no_statement2;
no_statement last; }
▪ Pseudocode
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
Compound Statement
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 (?:)
▪ 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
Example-6
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".
• 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).
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:
A robot navigating a maze must decide its next move based on obstacles ahead and to the left. Write a C++
program that:
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:
Syntax:
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
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;
}
Syntax:
for (initialization; Loop Continuation Test; update)
{
statement block;
}
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
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++.
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
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.
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:
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
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*/.
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;
int main()
cout << "local x in main's outer scope is " << x << endl;
int x = 7;
cout << "local x in main's inner scope is " << x << endl;
cout << "local x in main's outer scope is " << x << endl;
} // end main
// useLocal reinitializes local variable x during each call
cout << endl << "local x is " << x << " on entering useLocal" << endl;
++x;
++x;
cout << "local static x is " << x << " on exiting useStaticLocal" << endl;
cout << endl << "global x is " << x << " on entering useGlobal" << endl;
x *= 10;
cout << "global x is " << x << " on exiting useGlobal" << endl;
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.
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.
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
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.
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 );
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
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.
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.
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
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;
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 subscript
Array name
Row subscript
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 ];
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.
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
.
.
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".
Then the variable ‘rate’ is stored at a specific memory address and as an illustration, can be
depicted as follows:
In the above example:
In programming we can find this address by “&” operator. This operator is called address
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".
POINTER OPERATIONS
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
#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;
}
}
• 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.
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 -- 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
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.
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.
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;
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;
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
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
/*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
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
There are a few operations that are not possible with pointers. These are:
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.
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.
• 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.
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:
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
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
DELETE OPERATOR
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:
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;
}
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
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