Programming Fundamentals Lab Manual
Programming Fundamentals Lab Manual
Lab Manual
Superior University LahoreIntroduction to Programming
List of Experiments
No. Description
4 Conditional Statements
8 Functions
9 Array
1
Superior University LahoreIntroduction to Programming
Experiment no. 1
Introduction
What is a programming language?
C++ is immensely popular, particularly for applications that require speed and/or access to
some low-level features. C++ is high-level languages; other high-level languages you might
have heard of are Java, C and Pascal FORTRAN. As you might infer from the name “high-
level language,” there are also low-level languages, sometimes referred to as machine
language or assembly language. Loosely-speaking, computers can only execute programs
written in low-level languages. Thus, programs written in a high-level language have to be
translated before they can run. This translation takes some time, which is a small
disadvantage of high-level languages. But the advantages are enormous. First, it is much
easier to program in a high-level language; by “easier” I mean that the program takes less
time to write, it’s shorter and easier to read, and it’s more likely to be correct. Secondly, high-
level languages are portable, meaning that they can run on different kinds of computers with
few or no modifications. Low-level programs can only run on one kind of computer, and
have to be rewritten to run on another. Due to these advantages, almost all programs are
written in high-level languages. Low-level languages are only used for a few special
applications.
2
Superior University LahoreIntroduction to Programming
Object files are intermediate files that represent an incomplete copy of the program: each
source file only expresses a piece of the program, so when it is compiled into an object file,
the object file has some markers indicating which missing pieces it depends on. The linker
takes those object files and the compiled libraries of predefined code that they rely on, fills in
all the gaps, and spits out the final program, which can then be run by the operating system
(OS).
In C++, all these steps are performed ahead of time, before you start running a program. In
some languages, they are done during the execution process, which takes time. This is one of
the reasons C++ code runs far faster than code in many more recent languages. C++ actually
adds an extra step to the compilation process: the code is run through a preprocessor, which
applies some modifications to the source code, before being fed to the compiler. Thus, the
modified diagram is:
Experiment no. 6
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular
code lines with expressions but indications for the compiler's preprocessor. In this case the
directive #include<iostream> tells the preprocessor to include the iostream standard file. This
3
Superior University LahoreIntroduction to Programming
specific file (iostream) includes the declarations of the basic standard input-output library
in C++, and it is included because its functionality is going to be used later in the program.
Int main ()
The main function is the point by where all C++ programs start their execution,
independently of its location within the source code. It does not matter whether there are
other functions with other names defined before or after it – the instructions contained within
this function's definition will always be the first ones to be executed in any C++ program. For
that same reason, it is essential that all C++ programs have a main function. The word main is
followed in the code by a pair of parentheses (). That is because it is a function declaration: In
C++, what differentiates a function declaration from other types of expressions are these
parentheses that follow its name. Optionally, these parentheses may enclose a list of
parameters within them. Right after these parentheses we can find the body of the main
function enclosed in braces { }. What is contained within these braces is what the function
does when it is executed.
cout<<10/10<<endl<<10*10<<endl<<10+10<<endl<<10-10<<endl;
4
Superior University LahoreIntroduction to Programming
You can perform all the mathematical operation in one single line by inserting <<
output operators.
For Formula below, you have to include the header file: math.h (#include<math.h>)
Absolute: cout<<abs (-8) <<”\n”;means that it will give modulus of value given i.e. +ive
value
Exponent: cout<<exp (6) <<”\n”;
Power: cout<<pow (2, 9) <<"\n";means that 2 raise to power 9 i.e. 2^9.
Square Root: cout<<sqrt (16) <<”\n”;
Tokens
Tokens are the minimals chunk of program that has meaning to the compiler –the smallest
meaningful symbols in the language. Our code displays all 6 kinds of tokens:
High-Level Language: A programming language like C++ that is designed to be easy for
humans to read and write.
5
Superior University LahoreIntroduction to Programming
Portability: A property of a program that can run on more than one kind of computer
Formal Language: Any of the languages people have designed for specific purposes, like
representing mathematical ideas or computer programs. All programming languages are
formal languages.
Natural Language: Any of the languages people speak that have evolved naturally.
Object Code: The output of the compiler, after translating the program.
Syntax Error: An error in a program that makes it impossible to parse (and therefore
impossible to compile).
Logical Error: An error in a program that makes it does something other than what the
programmer intended.
Debugging: The process of finding and removing any of the three kinds of errors.
Experiment no. 2
The objective of this exercise is to understand variables and there data types use in
programming.
6
Superior University LahoreIntroduction to Programming
Introduction
CPU & Memory:
A computer acts on some data according to the instructions specified in a program and
produces the output. This computation is done by Central Processing Unit (CPU) of the
computer. A CPU of computer performs arithmetic operations such as addition, subtraction,
multiplication and division and also performs logical operation on the data such as comparing
two numbers.
Memory of a computer is the area where data and programs are stored. A computer memory
is made up of registers and cells which are capable of holding information in the form of
binary digits 0 and 1 (bits).This is the way information is stored in a memory just like we
memorize numbers using 0 to 9. Collection of 8 bits is called a byte. Normally the CPU does
not accessed memory by individual bits. Instead, it accesses data in a collection of bits,
typically 8 bits, 16 bit, 32 bit or 64 bit. The amount if bits on which it can operate
simultaneously is known as the word length of the computer.
When we say that Pentium 4 is a 32 bit machine, it means that it simultaneously operates on
32 bit of data. Data is stored in the memory at physical memory locations. These locations are
known as the memory address. It is very difficult for humans to remember the memory
addresses in numbers like 46735, so instead we name a memory address by a variable.
Variables
“A variable is a named location that stores a value. “When you create a new variable, you
have to declare what type it is and then the name of that variable.
Syntax:
Type of Variable Name of Variable;
The type of a variable determines what kind of values it can store. A char variable can
contain characters, and it should come as no surprise that int variables can store integers.
To create an integer variable, the syntax is:-
int a;
The statement below show that how to declare two variables in one instruction.
int b, c;
Data Types
Every variable in C++ can store a value. However, the type of value which the variable can
store has to be specified by the programmer. C++ supports the following inbuilt data types:
int (to store integer values), float (to store decimal values) and char (to store characters),
bool (to store Boolean value either 0 or 1) and etc.
7
Superior University LahoreIntroduction to Programming
A. Integer:
Integer (int) variables are used to store integer values like 34, 68704 etc.
To declare a variable of type integer, type keyword int followed by the name of the variable.
You can give any name to a variable but there are certain constraints, they are specified in
Identifiers section. For example, the statement
int sum; declares that sum is a variable of type int. You can assign a value to it now or later.
In order to assign values along with declaration use the assignment operator (=).
int sum = 25;
Assigns value 25 to variable sum.There are three types of integer variables in C++, short, int
and long int. All of them store values of type integer but the size of values they can store
increases from short to long int. This is because of the size occupied by them in memory of
the computer. The size which they can take is dependent on type of computer and varies.
More is the size, more the value they can hold. For example, int variable has 2 or 4 bytes
reserved in memory so it can hold 232= 65536 values. Variables can be signed or unsigned
depending they store only positive values or both positive and negative values. And short,
variable has 2 bytes. Long int variable has 4 bytes.
B. Float:
To store decimal values, you use float data type. Floating point data types
comes in three sizes, namely float, double and long double. The difference is in the length of
value and amount of precision which they can take and it increases from float to long double.
For example, statement
float average = 2.34;
Declares a variable average which is of type float and has the initial value 2.34
C. Character:
A variable of type char stores one character. It size of a variable of
type char is typically 1 byte. The statement
char name = 'c';
Declares a variable of type char (can hold characters) and has the initial values as character c.
Note that value has to be under single quotes.
D. Boolean:
A variable of type bool can store either value true or false and is mostly
used in comparisons and logical operations. When converted to integer, true is any non-zero
value and false corresponds to zero.
C++ imposes fairly strict rules on how you can name your variables:
● variable names must begin with a letter
8
Superior University LahoreIntroduction to Programming
9
Superior University LahoreIntroduction to Programming
Program should take the value of length and width from User
#include <iostream.h>
void main()
{
int length, width, area; //you can declare the variable in one line.
cin>>length;
cin>>width;
area = length * width;
cout<<"The area is: ";
cout<<area;
cout<<"\n\n";}
You can take the value from User in one line as Well.
#include <iostream.h>
void main()
{
int length, width, area; //you can declare the variable in one line.
cin>>length>>width;
area = length * width;
cout<<"The area is: ";
cout<<area;
cout<<"\n\n";
}
What is the difference of float data type from integer data type?
#include <iostream.h>
void main()
{
int a, b, c;
a=10;
b=3;
c=a/b;
cout<<"Answer is: ";
cout<<c;
cout<<"\n\n";
10
Superior University LahoreIntroduction to Programming
The output of this program is 3, but actually 10/3 = 3.33333, but whenever fraction comes the
int variable always takes the lower value like 10/6=1.66667 but the int variable will not
convert it to 2 it will take the lower value i.e. 1 and excludes the fraction.
Experiment no. 3
11
Superior University LahoreIntroduction to Programming
Introduction
Control Structures
Control structures are portions of program code that contain statements within them and,
depending on the circumstances, execute these statements in a certain way. There are
typically two kinds: conditionals and loops.
I. Conditionals
In order for a program to change its behavior depending on the input,
there must a way to test that input. Conditionals allow the program to check the values of
variables and to execute (or not execute) certain statements. C++ has if and switch-case
conditional structures.
II. Operators
An operator is a symbol that tells the compiler to perform a specific
mathematical or logical manipulation. C++ has four general classes of operators: arithmetic,
bitwise, relational, and logical.
C++ also has several additional operators that handle certain special situations.
1. Arithmetic
C++ defines the following arithmetic operators:
The operators +, –, *, and / all work the same way in C++ as they do in algebra. These can be
applied to any built-in numeric data type. They can also be applied to values of type char.
12
Superior University LahoreIntroduction to Programming
Both the increment and decrement operators can either precede (prefix) or follow (postfix)
the operand.
For example,
x = x + 1; can be written as ++x; // prefix form or as x++; // postfix form.
In this example, there is no difference whether the increment is applied as a prefix or a
postfix.
The following table shows the relative precedence of the relational and logical operators.
13
Superior University LahoreIntroduction to Programming
Experiment no. 4
The objective of this exercise is to get familiar with conditional loops in programming.
Conditional Loops
If Statement
The if keyword is used to execute a statement or block only if a condition is fulfilled.
Syntax
if (condition)
statement;
Where condition is the expression that is being evaluated. If this condition is true, statement
is executed. If it is false, statement is ignored (not executed) and the program continues right
after this conditional structure. For example, the following code fragment prints x is 100 only
if the value stored in the x variable is indeed 100:
if ( x == 100 )
cout<<”x is 100”;
If we want more than a single statement to be executed in case that the condition is true we
can specify a block using braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
In code below, only that if statement will be executed which condition will be true.
int a, b;
cin>>a>>b;
if(a == b) cout<<”a is equal to b”<<endl;
if(a != b) cout<<”a is not equal to b”<<endl;
if(a > b) cout<<”a is greater than b”<<endl;
if(a < b) cout<<”a is less than b”<<endl;
14
Superior University LahoreIntroduction to Programming
If-Else Statement
We can additionally specify what we want to happen if the condition is not fulfilled by using
the keyword else. Its form used in conjunction with if is:
Syntax
if (condition)
{
Statements;
}
else
{
Statements;
}
The following program demonstrates the if by playing a simple version of the “guess the
magic number” game. The program generates a random number, prompts for your guess, and
prints the message **Right ** if you guess the magic number. This program also introduces
another C++ library function, called rand ( ), which returns a randomly selected integer value.
It requires the <cstdlib>.
#include<iostream.h>
#include<cstdlib.h>
void main( )
{
int magic; // magic number
int guess; // user’s guess
magic = rand(); // get a random number
cout<<”enter your guess: ”;
cin>>guess;
if (guess==magic) cout<<” ** RIGHT ** ”;
else cout<<” . . . . SORRY YOU ARE WRONG . . . . “;
}
#include<iostream.h>
#include<cstdlib.h>
void main( )
{
int magic, guess;
magic = rand(); // get a random number
cout<<”enter your guess: ”;
cin>>guess;
if (guess==magic) cout<<” ** right ** ”;
else
{
15
Superior University LahoreIntroduction to Programming
If-Else-If Ladder
A common programming construct that is based upon nested ifs is the if-else-if ladder, also
referred to as the if-else-if staircase. It looks like this:
Syntax
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
else
statement;
The conditional expressions are evaluated from the top downward. As soon as a true
condition is found, the statement associated with it is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. The
final else often acts as a default condition; that is, if all other conditional tests fail, then the
last else statement is performed. If there is no final else and all other conditions are false, then
no action will take place.
#include<iostream.h>
void main( )
{
int x=10;
if(x==1) cout<< “x is one. \n”;
else if (x==2) cout<<”x is two. \n”;
else if(x==3) cout<<”x is three. \n”;
else if(x==4) cout<<”x is four. \n”;
else cout<<” x is not between 1 and 4.\n”;
}
16
Superior University LahoreIntroduction to Programming
Experiment no. 5
The objective of this exercise is to get familiar with basic for loop structure in
programming.
17
Superior University LahoreIntroduction to Programming
include an increase field but no initialization (maybe because the variable was already
initialized before).
Optionally, using the comma operator (,) we can specify more than one expression in any of
the fields included in a for loop, like in initialization, for example. The comma operator (,) is
an expression separator, it serves to separate more than one expression where only one is
generally expected. For example, suppose that we wanted to initialize more than one variable
in our loop:
n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i).
Because n is increased by one and i decreased by one, the loop's condition will become false
after the 50th loop, when both n and i will be equal to 50.
\\This program will display the numbers from 1 to 10 using for loop.
#include<iostream.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
cout<<i<<endl;
}
cout<<"\n\n";
}
\\This program will display the numbers from 10 to 1 using for loop.
#include<iostream.h>
void main()
{
int i;
for(i=10;i>0;i--)
{
q cout<<i<<endl;
}
cout<<"\n\n";
}
#include<iostream.h>
#include<stdlib.h> //you have to include this header file for pause command.
void main( )
{
int i=0;
for(;i++<10;)
{ cout<<i<<endl;
18
Superior University LahoreIntroduction to Programming
The statement
If(c==’A’)
checks whether the character entered is A. If the character is ‘A’ the loop terminates with
the help of statement
break;
If the character is not ‘A’ loop continues. The loop will continue as long as user does not
enter character ‘A’.
Jump Statements:
#include<iostream.h>
void main ( )
{
int c ;
for( c=10; c >=1 ; c-- )
19
Superior University LahoreIntroduction to Programming
{
cout<< n << endl;
if( n == 4)
{
cout<< “ counter stop at 4! ”<<endl;
break;
}
}
}
2. The goto statement :
Goto allows to make an absolute jump to another point in the program. You
should use this feature with caution since its execution causes an unconditional jump ignoring
any type of nesting limitations. The destination point is identified by a label, which is then
used as an argument for the goto statement. A label is made of a valid identifier followed by a
colon (:).
#include <iostream.h>
void main ( )
{
int n=10;
loop:
cout << "Loop is again going to start\n";
for( ;n > 0 ; n-- )
{
cout << n << ", ";
if (n == 1)
{
goto loop;
}
}
}
Experiment no. 6
20
Superior University LahoreIntroduction to Programming
The objective of this exercise is to get familiar with basic while loop structure in
programming.
Where statement may be a single statement or a block of statements. The expression defines
the condition that controls the loop, and it can be any valid expression. The statement is
performed while the condition is true. When the condition becomes false, program control
passes to the line immediately following the loop.
Write a program which will create the sequence of numbers from 1 to 26 using while loop.
Note the output of the following program and differentiate between them:
Write a program which will display the English language letters in both capital & small.
#include<iostream.h>
void main( )
{
int i;
char a = 'a';
i=0;
while(i<26)
{
cout<<a<<" ";
a++;
21
Superior University LahoreIntroduction to Programming
i++;
}
cout<<"\n";
a='a';
i=0;
while(i<26)
{
cout<<a<<" ";
a++;
i++;
}
}
do
statement
while (condition)
statement;
Its functionality is exactly the same as the while loop, except that condition in the do-while
loop is evaluated after the execution of statement instead of before, granting at least one
execution of statement even if condition is never fulfilled.
#include <iostream.h>
22
Superior University LahoreIntroduction to Programming
void main ( )
{
int n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}
while (n != 0);
}
Experiment no. 7
23
Superior University LahoreIntroduction to Programming
The objective of this exercise is to get familiar with switch structure in programming.
Switch
Switch case statements are a substitute for long if statements that compare a variable to
several "integral" values ("integral" values are simply values that can be expressed as an
integer, such as the value of a char). The basic format for using switch case is outlined
below.
Syntax:
switch ( test ) {
case 1 :
// Process for test = 1
...
break;
case 5 :
// Process for test = 5
...
break;
default :
// Process for all other cases.
...
}
#include<iostream.h>
24
Superior University LahoreIntroduction to Programming
Break:
Terminates the loop and transfers execution to the statement immediately following the loop
or switch.
Syntax:
while (condition)
{
statements;
}
Experiment no. 8
25
Superior University LahoreIntroduction to Programming
Functions
Functions helps in making a programming code more organized and reduces the number of
instructions. Use of functions is associated with reusability since the instructions enclosed by
the function body can be reused just by calling the function wherever required instead of
writing that set of instructions several times.
The most commonly used function/method is void main (). This function is a necessary part
of every program. There are several other function with which you are familiar like sqrt(),
exp(), abs(), etc. These functions come from the header file math.h. The details of these
functions have been implemented by the C++ developers. In this lab session, students will
learn to implement their own functions and make function calls. Consider the main function:
Syntax:
void main() // function header
{
// function body
}
Return type: In the above function, the return type is void. A function with void return type
does not return any value to the place where the function is called. A function may have any
other return type depending on the type of variable returned from the function.
Name of the function: Every function does have a name. The name of the function defined
above is main. The names of functions should be descriptive about the purpose for which the
function is implemented. For example, the function sqrt() indicates that it takes the square
root of the variable placed between the round brackets.
Parameter list: Any variable written between the round brackets in the function header
makes up the parameter list. The parameter list may have one or more variables. For example,
the function sqrt () takes only one parameter. The function POW (,) takes two parameters.
Example 1. A function square () with no return type and no parameter list. The function
square () is called in main method.
#include <iostream.h>
// the function implementation
void square() // function header
{
int s, num; // local variables
cout<<”enter the number to take square:”<<endl;
cin>>num; // taking number
s = num * num; // calculating square
26
Superior University LahoreIntroduction to Programming
void main()
{
cout<<”displaying square of a number:”<<endl;
square (); // function call
}
In the above program, the function square () has return type ‘void’ which means that the
function does not return any value. The number is taken as input from the user inside the
function and the square of that number is also printed inside the function.
Since the function computes the square of a number, the function can have the return type
‘int’. In that case, the function will return an integer value (square of the number) where the
function call is initially made. Consider the following program which is another version of
the program in Example 1.
Example 2. A function square () with return type ‘int’ and no parameter list. The function
square () is called in main method.
#include <iostream.h>
// the function implementation
int square() // function header
{
int s, num; // local variables
cout<<”enter the number to take square:”<<endl;
cin>>num; // taking number
s = num*num; // calculating square
return s; // returning value
}
void main()
{
int s; // local variable
cout<<”displaying square of a number:”<<endl;
s = square(); // function call
cout<<”square of the number is: ”<<s<<endl;}
In the above program, the input from the user is taken inside the function, the square of that
number is calculated and the answer is returned to the main method. Always make sure that
the value returned from the function is consistent with the return type of the function
specified in the header. Also the value returned from the function is stored in a variable with
appropriate data type. As in the above program, the function returns an ‘int’ value and the
value is stored in an ‘int’ type variable in the main method. The above function can also be
written as below without using another variable‘s’:
27
Superior University LahoreIntroduction to Programming
In the above implementation, the local variable‘s’ is not used. This function gives the same
result as before. Consider another implementation of the same function but with a function
parameter. Here, the number from the user is not taken inside the function, but is passed from
the main method. The number is taken from the user in the main method and is passed to the
function as a function parameter. The function calculates the square of that number and
returns the value in the main method, from where the function was called.
Example 3.
#include <iostream.h>
// the function implementation
int square(int num) // function header
{
int s; // local variable
s = num*num; //calculating square
return s; // returning value
}
void main()
{
int s, n1; // local variables
cout<<”enter the number to take square:”<<endl;
cin>>n1; // taking number
s = square(n1); // function call
cout<<”square of the ”<<n1<<” is: ”<<s<<endl;
}
In the above implementation, the number taken from the user (in the main method) is in the
variable ‘n1’. This variable is passed to the function square () as a parameter. In the
parameter part, the value of ‘n1’ is copied in the variable ‘num’, which is then passed inside
the function square (). Inside the function, the square of that number is calculated, stored in a
local variable‘s’ and the value in‘s’ is returned to the main method.
Consider the following program which takes the maximum of three numbers. The three
numbers should be passed to the function from the main method and maximum of these three
numbers will be returned back to the main method.
Example 4.
#include <iostream.h>
// the function implementation
int maximum(int a, int b, int c) // function header
{
int n = a; // local variable
if(n < b)
n = b;
28
Superior University LahoreIntroduction to Programming
if(n < c)
n = c;
return n; // returning value
}
void main()
{
int n1, n2, n3, max;
cout<<”enter the numbers to find maximum:”<<endl;
cin>>n1>>n2>>n3;
max = maximum(n1,n2,n3);
cout<<”maximum of the three numbers is ”<<max<<endl;
}
Experiment no. 9
29
Superior University LahoreIntroduction to Programming
Array
An array is a series of elements of the same type placed in contiguous memory locations that
can be individually referenced by adding an index to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having to
declare 5 different variables, each one with a different identifier. Instead of that, using an
array we can store 5 different values of the same type, int for example, with a unique
identifier.
For example, an array to contain 5 integer values of type int called billy could be represented
like this:
Where each blank panel represents an element of the array, that in this case are integer values
of type int. These elements are numbered from 0 to 4 since in arrays the first index is always
0, independently of its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for
an array in C++ is:
Syntax:
type name [elements];
Where type is a valid type (like int, float...), name is a valid identifier and the elements field
(which is always enclosed in square brackets []), specifies how many of these elements the
array has to contain.
Therefore, in order to declare an array called billy as the one shown in the above diagram it is
as simple as:
int billy [5];
Initializing Array:
When declaring a regular array of local scope (within a function, for example), if we do not
specify otherwise, its elements will not be initialized to any value by default, so their content
will be undetermined until we store some value in them. The elements of global and static
arrays, on the other hand, are automatically initialized with their default values, which for all
fundamental types this means they are filled with zeros.In both cases, local and global, when
we declare an array, we have the possibility to assign initial values to each one of its elements
by enclosing the values in braces { }. For example:
The amount of values between braces { } must not be larger than the number of elements that
we declare for the array between square brackets [ ]. For example, in the example of array
billy we have declared that it has 5 elements and in the list of initial values within braces { }
we have specified 5 values, one for each element.
30
Superior University LahoreIntroduction to Programming
When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the
array that matches the number of values included between braces { }:
int billy [] = { 16, 2, 77, 40, 12071 };
After this declaration, array billy would be 5 ints long, since we have provided 5 initialization
values.
Accessing the values of Array:
In any point of a program in which an array is visible, we can access the value of any of its
elements individually as if it was a normal variable, thus being able to both read and modify
its value. The format is as simple as:
Syntax:
name[index]
Following the previous examples in which billy had 5 elements and each of those elements
was of type int, the name which we can use to refer to each element is the following:
For example, to store the value 75 in the third element of billy, we could write the following
statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable called a, we
could write:
a = billy[2];
Therefore, the expression billy[2] is for all purposes like a variable of type int.
Notice that the third element of billy is specified billy[2], since the first one is billy[0], the
second one is billy[1], and therefore, the third one is billy[2]. By this same reason, its last
element is billy[4]. Therefore, if we write billy[5], we would be accessing the sixth element
of billy and therefore exceeding the size of the array.
In C++ it is syntactically correct to exceed the valid range of indices for an array. This can
create problems, since accessing out-of-range elements do not cause compilation errors but
can cause runtime errors. The reason why this is allowed will be seen further ahead when we
begin to use pointers.
At this point it is important to be able to clearly distinguish between the two uses that
brackets [ ] have related to arrays. They perform two different tasks: one is to specify the size
of arrays when they are declared; and the second one is to specify indices for concrete array
elements. Do not confuse these two possible uses of brackets [ ] with arrays.
31
Superior University LahoreIntroduction to Programming
Lab # Experiment
Lab Task 01
1. Software Installation.
32
Superior University LahoreIntroduction to Programming
Lab Task 02
6. Write a program which accept two numbers and print their sum.
7. Write a program which accept temperature in Fahrenheit and print it in Centigrade.
8. Write a program which accepts a character and display its ASCII value.
9. Write a program to swap the values of two variables.
10. Write a program to calculate area of circle.
11. Fakhar’s basic salary is input through the keyboard. His dearness allowance is 40% of
basic salary, and house rent allowance is 20% of basic salary. Write a program to
calculate his gross salary.
12. The length & breadth of a rectangle and radius of a circle are input through the keyboard.
Write a program to calculate the area & perimeter of the rectangle, and the area &
circumference of the circle.
Lab Task 03
13. Write a program to check whether the given number is positive or negative
14. Write a program to check whether the given number is even or odd
15. Write a program to swap value of two variables without using third variable.
16. Write a program which input three numbers and display the largest number
17. Write a program which accepts a character and display its next character.
18. Write a program to check whether input character is vowel or not.
19. Write a program to check whether input number is a devisor of 7 or not.
20. Write a program that reads two integers and determines and prints if the first is a multiple
of the second. [Hint: Use the modulus operator.]
21. Write a program that asks the user to enter two integers, obtains the numbers from the
user, and then prints the larger number followed by the words "is larger." If the numbers
are equal, print the message "These numbers are equal."
Lab Task 04
33
Superior University LahoreIntroduction to Programming
23. If the ages of Asad, Ali and Asghar are input by the user, write a program to determine
the youngest of the three.
24. Write a program to check whether a triangle is valid or not, when the three angles of the
triangle are entered by the user. A triangle is valid if the sum of all the three angles is
equal to 180 degrees.
25. Write a program that takes age as input and prints "You can't drive." if age is less than
18, and "You can drive but carefully." if age is greater than or equal to 18 and less than
20.
26. Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for up to 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
27. Write a program to find the roots of and quadratic equation of type ax2+bx+c where a is
not equal to zero.
28. The marks obtained by a student in 5 different subjects are input by the user. The student
gets a division as per the following rules: Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division Percentage between 40 and 49 - Third
division Percentage less than 40 - Fail Write a program to calculate the division obtained
by the student.
Lab Task 05
29. Any character is entered by the user; write a program to determine whether the character
entered is a capital letter, a small case letter, a digit or a special symbol. The following
table shows the range of ASCII values for various characters.
34
Superior University LahoreIntroduction to Programming
30. Write a C++ program which should ask for birth month from user and find its assigned
star name with the help of if statement. E.g August= LEO
31. Write a C++ program which should find name of month with the help of switch
statement. E.g 12= December
32. Write a program that prompts the user to enter the weight of a person in kilograms and
outputs the equivalent weight in pounds. Output both the weights rounded to two decimal
places. (Note that 1 kilogram = 2.2 pounds.) Format your output with two decimal
places.
33. Write a program that inputs a five-digit integer, separates the integer into its digits and
prints them separated by three spaces each. [Hint: Use the integer division and modulus
operators.] For example, if the user types in 42339, the program should print: 4 2 3 3
9.
Lab Task 06
34. If a five-digit number is input through the keyboard, write a program to reverse the
number.
35. If a four-digit number is input through the keyboard, write a program to obtain the sum
of the first and last digit of this number.
36. Running on a particular treadmill you burn 3.9 calories per minute. Write a program that
uses a loop to display the number of calories burned after 10, 15, 20, 25, and 30 minutes.
37. Write a program that asks the user to enter the amount that he or she has budgeted for a
month. A loop should then prompt the user to enter each of his or her expenses for the
month, and keep a running total. When the loop finishes, the program should display the
amount that the user is over or under budget. The program will stop when the user enters
0 as an expense. Sample run:
35
Superior University LahoreIntroduction to Programming
38. Write a program that accepts as input the mass, in grams, and density, in grams per cubic
centimeters, and outputs the volume of the object using the formula: density = mass /
volume. Format your output to two decimal places.
39. Write a program with a loop that lets the user enter a series of integers. The user should
enter -99 to signal the end of the series. After all the numbers have been entered, the
program should display the largest and smallest numbers entered.
Sample run:
Lab Task 07
40. Write a program to print the factorial of a number.
SAMPLE INPUT: 3
SAMPLE OUTPUT: 6
41. Write a program that takes N as an input and print the greatest N-digit number.
SAMPLE INPUT: 3
SAMPLE OUTPUT: 999
42. Write a program to print the following series in same pattern.
2, 4, 8, 16, 32, 64 … 1024
43. Write a program to display all even numbers till 150.
44. Write a program to display all odd numbers till 100.
45. Write a program to display all the devisors of 7 till 150.
46. Write a program to display all the devisors of a number given by user till the range which
will also defined by user.
47. Write a program to display the answer of following series.
1+2+3+4+5+6 … +n.
Where n will be given by user.
Lab Task 08
Computer Lab mid Term Exams.
36
Superior University LahoreIntroduction to Programming
Lab Task 09
48. Write a program to take marks of 4 subjects for 15 students and show the total marks
obtained by the students.
49. Write a computer program that prompts the user to input elapsed time in seconds. The
program then outputs the elapsed time in hours, minutes and seconds. (For example if the
elapsed time is 9630 seconds, then the output is 2 : 40 : 30)
50. Suppose a, b and c denotes the length of the sides of a triangle. Then the area of the
triangle can be calculated using the formula: 𝑠 𝑠−𝑎 𝑠−𝑏 𝑠−𝑐 where s = (1 / 2) (a + b +
c). Design an algorithm and computer program to find the area of a triangle.
Here user will input the values of a,b & c.
(Hint: Use the predefined function sqrt();)
51. Write a computer program that prompts the user to input the elapsed time for an event in
hours, minutes and seconds. The program then outputs the elapsed time in seconds.
52. Write a program to take the value of v, x, y, z from user and calculates the following
expression.
53. Write a function to obtain the first n numbers of Fibonacci sequence. Where n will be
taken from user in main(). In a Fibonacci sequence the sum of two successive terms
gives the third term.
Example: 1 1 2 3 5 8 13 21 34 …
Lab Task 10
54. Write a Program to print the following Patterns. (Using For Loop)
37
Superior University LahoreIntroduction to Programming
Lab Task 11
55. Practice All above the Patterns using while loop
Lab Task 12
56. Write a program which takes 10 elements in an array and print there values.
57. Write a program which takes 10 elements in an array and find out the random number
from this array.
58. Write a program which takes 2 arrays and print the sum of those arrays.
59. Write a program which prints the following output using two dimension array.
1 2 3
4 5 6
7 8 9
38
Superior University LahoreIntroduction to Programming
Lab Task 13
60. Write a non-parameterized function which prints HELLO WORLD.
61. Write a parameterized function which prints input string as arguments.
62. Write a non-parameterized function which input two values from user and print sum of
those values.
63. Write a parameterized function which input two values from user and print sum of those
values.
64. Write a Program which input two values from user and print +,-,*,/ of those values by
using functions.
Lab Task 14
65. Write a Student Management System which save minimum 5 Students record using
arrays and function.
Lab Task 15
Computer Lab Final Term Exams.
39