Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
284 views

Programming Fundamentals Lab Manual

Uploaded by

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

Programming Fundamentals Lab Manual

Uploaded by

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

Programming Fundamentals

Lab Manual
Superior University LahoreIntroduction to Programming

List of Experiments

No. Description

1 Introduction to Programming in C++

2 Variables, Constants & Data Types

3 Operators (Relational & Logical)

4 Conditional Statements

5 For Loop Statements

6 While Loops Statements

7 Switch & Break Statements

8 Functions

9 Array

Computer Science & Information Technology


Department

1
Superior University LahoreIntroduction to Programming

Experiment no. 1

The objective of this exercise is to understand the programming basic concepts.


Introduction to Programming in C++

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.

Why Use a Language Like C++?


At its core, a computer is just a processor with some memory, capable of running
tiny instructions like “store 5 in memory location 23459.” Why would we express a program
as a text file in a programming language, instead of writing processor instructions?
The advantages:

1. Conciseness: programming languages allow us to express common sequences of


commands more concisely. C++ provides some especially powerful short hands.
2. Maintainability: modifying code is easier when it entails just a few text edits, instead of
rearranging hundreds of processor instructions.
3. Portability: different processors make different instructions available. Programs written as
text can be translated into instructions for many different processors; one of C++’s strengths
is that it can be used to write programs for nearly any processor.

The Compilation Process


A program goes from text files (or source files) to processor instructions as follows:
A compiler is a program that reads a high-level program and translates it all at once, before
executing any of the commands. Often you compile the program as a separate step, and then
execute the compiled code later. In this case, the high-level program is called the source code,
and the translated program is called the object code or the executable.

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

First Program in C++


Source Code Output
//my first program in C++ Hello World!
#include <iostream>
using namespace std;
voidmain ()
{
cout << "Hello World!";
}

// my first program in C++


This is a comment line. All lines beginning with two slash signs (//) are considered comments
and do not have any effect on the behavior of the program. The programmer can use them to
include short explanations or observations within the source code itself.

#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.

Using namespace std;


All the elements of the standard C++ library are declared within what is called a namespace,
the namespace with the name std. So in order to access its functionality we declare with this
expression that we will be using these entities. This line is very frequent in C++ programs
that use the standard library.

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 << "Hello World!";


This line is a C++ statement. This statement performs the only action that generates a visible
effect in our first program. Cout represents the standard output stream in C++, and the
meaning of the entire statement is to insert a sequence of characters (in this case the Hello
World sequence of characters) into the standard output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we
needed to include that specific file and to declare that we were going to use this specific
namespace earlier in our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark
the end of the statement and in fact it must be included at the end of all expression statements
in all C++ programs (one of the most common syntax errors is indeed to forget to include
some semicolon after a statement).

Source Code Output


//my second program in C++ 20
#include <iostream> 100
using namespace std; 0
voidmain () 1
{
cout << 10+10<<endl;
cout<<10*10<<endl;
cout<<10-10<<endl;
cout<<10/10<<endl;}
You can also do mathematical operations using cout statements like above. You can also do
all the mathematical operation using single cout statement like this:

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”;

Logarithm & Trigonometric Functions:


Natural Algorithum: cout<< log (3) <<”\n”;Gives the natural logarithm of 3.
Sine: cout<< sin (45) <<”\n”;Gives the Sine value of 45 degrees in radians.
Cosine: cout<<cos (45) <<”\n”;Gives the cosine value of 45 degrees in radians.
Tangent: cout<<sin (45) <<”\n”;Gives the Tangent value of 45 degrees in radians.
Inverse of Sine: cout<<asin (30) <<”\n”;Gives the inverse sine of 30 degrees in radians.
Inverse of Cosine: cout<<acos (30) <<”\n”;Gives the inverse cosine of 30 degrees in radians.
Inverse of Tangent:cout<<atan (30) <<”\n”;Gives the inverse tangent of 30 degrees in
radians.
Hyperbolic Sine: cout<<sinh (60) <<”\n”;Gives the hyperbolic sine of 60 degrees in radians.
Hyperbolic Cosine: cout<<cosh (60) <<”\n”;Gives the hyperbolic cosine of 60 degrees in
radians.
Hyperbolic Tangent: cout<<tanh (60) <<”\n”;Gives the hyperbolic tangent of 60 degrees in
radians.

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.

Low-Level Language: A programming language that is designed to be easy for a computer


to execute also called “machine language” or “assembly language.”

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.

Compile: To translate a program in a high-level language into a low-level language, all at


once, in preparation for later execution.

Source Code: A program in a high-level language, before being compiled.

Object Code: The output of the compiler, after translating the program.

Executable: Another name for object code that is ready to be executed.

Algorithm: A general process for solving a category of problems.

Bug: An error in a program.

Syntax: The structure of a program.

Syntax Error: An error in a program that makes it impossible to parse (and therefore
impossible to compile).

Run-Time Error: An error in a program that makes it fails at run-time.

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

Variables, Constants & Data Types

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;

Declaring a variable in C++:


char a;

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

● variable names are "case-sensitive" (i.e., 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)

8
Superior University LahoreIntroduction to Programming

Assignment Operator (=)


Now that we have created some variables, we would like to store values in them.We do that
with an assignment statement.

Char a; \\Declaring a variable of character type.


a = ‘H’; \\Assigning a character value to the character variable.

● When you declare a variable, you create a named storage location.

● When you make an assignment to a variable, you give it a value.

Declaration of Variable of Data Type (Integer)


\\Assigning a Fixed Value to Variable
#include <iostream.h>
void main()
{
int length;
length = 7;
cout<<"The Length is: ";
cout<<length;
cout<<"\n\n";
}

Assign the Value to Variable through Keyboard


Remember to take value from keyboard, we use cin with input operator >>.
#include <iostream.h>
void main()
{
int length;
cin>>length;
cout<<"The Length is: ";
cout<<length;
cout<<"\n\n";

9
Superior University LahoreIntroduction to Programming

Calculate the Area of the Box


#include <iostream.h>
void main()
{
int length;
int width;
length=7;
width=5;
cout<<"The area is: ";
cout<<length*width;
cout<<"\n\n";
}

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.

Variable can be declared with float.


#include <iostream.h>
void main()
{
float a, b, c;
a=10;
b=3;
c=a/b;
cout<<"Answer is: ";
cout<<c;
cout<<"\n\n";
}

Experiment no. 3
11
Superior University LahoreIntroduction to Programming

The objective of this exercise is to get familiar with operators in programming.

Operators (Relational & Logical)

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.

2. Increment & Decrement (++ and --)


The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
Therefore,

x = x + 1; is the same as x++;


x = x -1; is the same as --x;

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 precedence of the arithmetic operators is shown here:

3. Relational & Logical Operators


Relational refers to the relationships that values can have with one another, and
logical refers to the ways in which true and false values can be connected together. Since the
relational operators produce true or false results, they often work with the logical operators.
In C++, not equal to is represented by != and equal to is represented by the double equal sign,
==.

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 . . . . “;
}

Nested If’s Statement


A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. The main thing to remember about nested ifs in C++ is that an else
statement always refers to the nearest if statement that is within the same block as the else
and not already associated with an else. Here is an example:

#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

cout<<” . . . . sorry you are wrong . . . . “;


If (guess > magic) cout<<” YOUR GUESS IS TOO HIGH .\n ”;
else cout<<” YOUR GUESS IS TOO LOW. \n ”;
}
}

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.

The following program demonstrates the if-else-if ladder:

#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.

Iteration Structures (Loops)


Loops have as purpose to repeat a statement a certain number of times or while a condition is
fulfilled.
“A statement that executes repeatedly while a condition is true or until some condition is
satisfied.”

The FOR Loop


Syntax
for (initialization; condition; increase)
statement;

For repeating a block, the general form is


for (initialization; expression; increment)
{
statement sequence;
}
Its main function is to repeat statement while condition remains true, but the for loop
provides specific locations to contain an initialization statement and an increase statement.
So this loop is specially designed to perform a repetitive action with a counter which is
initialized and increased on each iteration.

It works in the following way:


1. Initialization is executed. Generally it is an initial value setting for a counter variable. This
is executed only once.
2. Condition is checked. If it is true the loop continues, otherwise the loop ends and statement
is skipped (not executed).
3. Statement is executed. As usual, it can be either a single statement or a block enclosed in
braces { }.
4. Finally, whatever is specified in the increase field is executed and the loop gets back to
step 2.

// countdown using a for loop


#include <iostream.h>
void main ( )
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "fire!\n";
}
The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon signs between them must be written. For example we could write: for (;n<10;) if
we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to

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

system("pause"); // At this stage I want to pause my program


}
cout<<"\n\n";
}

\\ Note the output of this program.


#include<iostream.h>
void main ( )
{
char c;
for( ; ; )
{ cout<<”enter the character : ”<<endl;
cin>>c;
if( c== ‘A’)
break; }
}

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’.

\\ Note the output of this program.


#include<iostream.h>
void main ( )
{
Int c=0, i=0 ;
for( ; i <= 10 ; i++ )
{ cout<<”Printing the value of loop variable : ”<<endl;
cout<< i <<endl ;
c= c+i ;
}
cout<< “ the sum is : ”<< c << endl;
}
This program will show the sum of all the ten values.

Jump Statements:

1. The break statement:


Using break we can leave a loop even if the condition for its end is not fulfilled. It
can be used to end an infinite loop, or to force it to end before its natural end.

#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.

The While Loop:


Syntax

The general form of the while loop is


while (expression)
statement;

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++;
}
}

Write a program to enter and display the matrix.


#include<iostream.h>
void main()
{
int a[2][2], i, j;
i=0;
while( i< 3)
{j=0;
while(j<3){
cin>>a[i][j];
j++;}
i++;}
i=0;
while( i< 3)
{j=0;
while(j<3)
{cout<<a[i][j];
cout<<" ";
j++;
}
cout<<"\n";
i++; }
}

The Do-While Loop:


Syntax

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 Break Statements

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.
...
}

● The expression, just test in this case, is evaluated.


● The case labels are checked in turn for the one that matches the value.
● If none matches, and the optional default label exists, it is selected, otherwise control
passes from the switch compound statement
● If a matching label is found, execution proceeds from there. Control then passes down
through all remaining labels within the switch statement. As this is normally not what
is wanted, the break statement is normally added before the next case label to transfer
control out of the switch statement. One useful exception occurs when you want to do
the same processing for two or more values. Suppose you want values 1 and 10 to do
the same thing, then:-
case 1 :
case 10:
// Process for test = 1 or 10
break;
works because the test = 1 case just "drops through" to the next section.

#include<iostream.h>

24
Superior University LahoreIntroduction to Programming

using namespace std;


int main(void)
{
int day;
cout<<”Enter day of the week between 1-7”;
cin>>day;
switch(day)
{
case 1:
cout<<”Monday”;
case 2:
cout<<”Tuesday”;
.
.
.
.
case 6:
cout<<”Saturday”;
default:
cout<<”Sunday”;
}
}

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

The objective of this exercise is to get familiar with functions in 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
}

The function header is made up of the following parts:

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

cout<<”square of ”<<num<<” = ”<<s<<endl; // printing square


}

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’:

int square() // function header


{

27
Superior University LahoreIntroduction to Programming

int num; // local variables


cout<<”enter the number to take square:”<<endl;
cin>>num; // taking number
return num*num; // returning value
}

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

The objective of this exercise is to get familiar with arrays in 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:

int billy [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:

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.

● int billy[5]; // declaration of a new array

● billy[2] = 75; // access to an element of the array.


Lab Tasks

31
Superior University LahoreIntroduction to Programming

Lab # Experiment

Write a prescribed note on


a) Main data types in C++.
01 b) Binary Operators
c) Header Files
d) Compiler & Interpreter
02 What are the rules for variable name?
03 Implementation of different programs using different data types (int, float, double
and Char).
04 Write a Program which takes two numbers input from user and give the sum of
these numbers.
05 Implementation of different programs using for loops.
06 Implementation of different programs using While loops.

07 Mid Term Lab Assignment.

08 Implementation of different programs using do while loops.

09 Implementation of different programs using decision If Else.

10 Implementation of different programs using decision Nested If Else.

11 Implementation of different programs using decision Switch Cases.


12 Implementation of different programs using normal functions.

13 Implementation of different programs using arrays.

14 Implementation of different programs using multi-dimensional arrays.

15 Final Term Lab Assignment.

Lab Task 01
1. Software Installation.

32
Superior University LahoreIntroduction to Programming

2. Write a program to print HELLO WORLD on screen.


3. Write a program to print Your Name Class Roll No etc on screen.
4. Write a program to print HELLO WORLD on screen by using variables and data types
5. Data Types and Variable declaration Programs.

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

22. What is the output of following program?


int result = 4 + 5 * 6 + 2;
cout << result;
int a = 5 + 7 % 2;
cout << a;

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

You might also like