0% found this document useful (0 votes)
52 views104 pages

Submitted To:: Mam Sana Nazeer Submitted by

The document is a lab manual submitted by Akhlaq Ahmad to Mam Sana Nazeer for Programming Fundamentals Lab No. 01. It provides an overview of the features of the integrated development environment (IDE) for C++, including invoking the IDE, using the menu bar, and functions of the file, edit, and compile menus. It also describes opening files from the command line, compiling and linking files to create an executable, and setting the IDE environment.

Uploaded by

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

Submitted To:: Mam Sana Nazeer Submitted by

The document is a lab manual submitted by Akhlaq Ahmad to Mam Sana Nazeer for Programming Fundamentals Lab No. 01. It provides an overview of the features of the integrated development environment (IDE) for C++, including invoking the IDE, using the menu bar, and functions of the file, edit, and compile menus. It also describes opening files from the command line, compiling and linking files to create an executable, and setting the IDE environment.

Uploaded by

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

Department Of computer Science

The Islamia University of Bahawalpur

Programming Fundamentals

Lab Manual

Submitted to:
Mam Sana Nazeer

Submitted By:
Akhlaq Ahmad
Roll No:
S21BDOCS1M01052
Session:
Spring-21
Lab No.01
Objective:
Study the features of Integrated Development Environment (IDE) for C++ language
THEORY
IDE basics
C language features an integrated development environment (IDE) as a programmer
platform. The IDE screen, which initially displays only a menu bar at the top of the screen
and status line below, will appear. The menu bar displays the menu names, File, Edit,
Search, Run and so no. The status line tells you what various function keys will do.
INTEGRATED DEVELOPMENT ENVIRONMENT
Invoking the IDE

To activate the IDE, all you need to do as type “TC” at the DOS prompt and press
Enter. E.g. C: \TC\BIN\TC
Using Menu Bar
The menu bar is used either to tell turbo C to do something Such as executes a
program or compile a program, or to set an environment options etc. When you first
invoke the IDE the menu bar will be active. (if for some reason the main menu is not
active press F10 to reactive it) To select different menus move the Highlight left and
right with the cursor arrow keys. To cause the highlighted menu to drop down so you
can see its contents press the down cursor key. Another approach to viewing a menu
is to press Alter key and the first letter of the menu name. You would press Alter + F
for the File Menu. To close the menu and return to the menu bar press Esc key.
File Menu
The file menu provide command for
 Creating New File
 Opening Existing Files
 Saving Files
 Changing Directories
 Printing Documents
 Shelling To Dos
 Quitting C

o New: To write a program Open File menu and select New. A new window will
appear on the screen with double line border. New Edit Windows with the default
name NONAMEXX.CPP (xx stand for a number from 00 to 31). These
NONAME files are used as temporary edit buffer.
o Open: The open command Displays the Open a File dialog box, where you can
select a program file to open in a window. Pressing the F3 key can also complete
this operation
o Save: The Save command saves the file that's in the active window to disk (this
menu item is disable if there is no active window). Pressing the F2 key can also
complete this operation
o Save As: Save As command opens the Save File As dialog box, where you can
save the file in the active Edit window under a different name, in the different
directory, or on the different drive.
o Print: The Print command prints the contents of the active edit, output, or
message window.
o Dos Shell: With the Dos Shell you can leave the turbo C environment
temporarily to perform a dos command or to enter another program. To return to
turbo C type EXIT at the Dos prompt, then press Enter.
o Quit: The Quit command exists turbo c, remove it from the memory, and return it you
to Dos.

Edit Menu
o Undo: Undo command takes back the last editing command you performed on a line.
o Redo: Redo command reverses the effect of the most recent Undo command.
o Cut: The Cut command removes the selected text from your document and places
the text in the clipboard. You can choose Edit | Paste to paste thatt text on other place.
o Copy: Copy command leaves the selected text intact and places an exact copy of it
in the clipboard.
o Paste: Paste command inserts the text from the clipboard into the current window at
the cursor position.
o Clear: Clear command removes the selected text but does not put it into the clipboard.

Opening file from command line


C language program can be opened from the command line an well. This can be
done by typing TC followed by the file name, when you first invoke the IDE.

C:\ TC\ BIN\ TC filename (TC HELLO.C)

Making the.exe file


After the program code is completed and the source is written, you must turn it into an
executable file. It includes different tasks to be performed on the file, which are
Compiling
It is the process in which source code is translated into machine understandable
language. "Compiler" Which is the part of the IDE, translate this source code into another
file, consisting of machine language.
Linking
Program may need to be combined with various library routines and functions. The
Linking process combines these files into single executable file.

The text editor produces the .c source file, which go to compiler, which produce .obj files,
which goes to linker, which produce the .exe files.
You can compile your program from main menu by selecting Compile | Compile. You
can link your program from main menu by selecting Compile | Link.
You can execute your program from main menu by selecting Run | Run.
Pressing the Alt+F9 can also perform the Compile operation.
Pressing the Clrl+F9 can also perform the Run operation.
Compiling and Linking from the command line:

You can compile and link a file from command line interface as well. To compile and
link with the command line system, programmer must first generate a source(.c) file using
any editor. To compile and linking any program from Dos prompt, you would enter the
following:
C:TC \ BIN tcc filename (tcc hello.c)
This produces the object and executable file just as the IDE does.
Setting the environment of the IDE

You can set the foreground and background colors of the IDE elements (Menus. Dialog
boxes, Edit window etc) by selecting Options | Environment | Color.
You have to also specify the Path in IDE, where the header file and Libra, tiles are
present in the turbo C compiler, This can be done by selecting Options j Directories. E.g.
C:\TC\INCLUDE (For include directories).
C:\TC\LIB (For library files)
Lab Solution:

Programming with the Dev C++ IDE

(1) Introduction to the IDE:


Dev-C++ is a full-featured Integrated Development
Environment (IDE) for the C/C++ programming language. It offers to the programmer a simple and
unified tool to edit, compile, link, and debug programs. It also provides support for the management of
the files of a program in “projects” containing all the elements required to produce a final executable
program.

Dev-C++ features are:


 Support GCC based compilers
 Integrated debugging
 Class Browser
 Debug variable Browser
 Code Completion
 Function Listing
 Project Manager
 Customizable syntax highlighting editor
 Quickly create Windows, console, static libraries and DLL
 Support of templates for creating your own project types
 Makefile creation
 Edit and compile Resource files

File:
File menu provides commands for following
Creating new files
Opening existing files
Saving files
Changing directories
Printing documents

Edit:
Edit menu provides following facilities
Undo ,Redo ,Cut, Copy,Paste the work.
We can also change the colors of identifies, symbols etc.

Execute:
This menu provides the facility to compile, run or link a program by just clicking on
what we want to do.

(2) First steps:


Following are the steps to make any program:
1. Create a project
The type of application and the programming language to be used are specified.
2. Write source code
Write the program in C++ and save the source code file.
3. Compile and link the code
The source code is compiled and linked to generate a running program. Other files of
the project may be created.
4. Fix compilation errors, if any
If the syntax of the program is not correct, the compilation fails and the compiler
generates a message related to the error. We must correct the errors.
5. Run the program
Run the program to confirm proper functioning.
6. Fix execution errors, if any
If the actions performed by the program are not as expected, it is necessary to correct
the source code. It may be good to use the debugger to find complex errors.

Project creation:
Following are the steps used to make a project in DEV C++
(I) Start Dev-C++ from program menu or shortcut
(ii) Create a project
Before creating the source code file, it is necessary to create a project (File > New > Project).
Options:
Console application
Name (name of the project)
C++ Project (for C++ language)
Select the folder to store the files in the next window.
After selecting the folder where the project configuration file (.dev) will be saved, the IDE
generates a basic source code file (by default, main.cpp).
Following types of files are created:
Project file .dev Project configuration data
Makefile .win Required for the compilation process. Manages
program dependencies and includes instructions for
the linker
Source code file .cpp Source code
Object file .o Object code resulting from the compilation of the
source code.
Executable file .exe Executable application
Once the project has been created, we can start writing our C++ program.
The editor highlights with different colors keywords and other elements of the C language.:
Light blue for comments
Green for included libraries
Red for text strings
Bold black for C++ keywords

Compilation and link:


To run a program, the source code must be compiled and linked. Dev-C++ performs the
complete process by clicking the Compile button (or Ctrl + F9).
While the compilation and link process is being performed, the IDE shows a dialog with related
information. If the process is successful, the window shows the message Done.

Fixing compilation errors


Compilation errors are errors that are detected by the compiler. To correct compilation errors, it is
recommended to solve the first one and then to re-compile the program again. Dev-C++ underlines in
red the line of code where the compilation error has been detected.
Running the program
As a result of the link process, an executable program is created. To run this program, we have
to click the Run button (Ctrl + F10). We can also find the executable program (.exe) in
the project folder and double-click on it. It is also possible to compile and run the program in a single
step by clicking the Compile & Run button (F9).

Fixing execution errors


Developing a syntactically-correct program does not means that it performs the required procedures.
Complex programs are usually the logic implemented & logical errors in the source code does not lead
to the expected behavior.
The IDE includes a debugger, which is a supporting tool to find runtime errors. To use the debugger, it
is necessary to modify the compiler options to include debugging information in the object and the
executable files (Tools > Compiler Options > Compiler). This is done by adding the –g parameter to the
calls to the compiler and the linker.
Lab No.02

OBJECTIVE:

Study the basic structure Of C++ program


Write a program that declares different variables and data types.

THEORY

In order to write program in any programming language, it is necessary to understand the


basic structure of the program, its command and syntax.

Major Parts of C program

main() This marks the point where the C programs begins execution.
Required for all programs.
() Must appear immediately after main. Information that will be used by
the program is usually contained within that braces.
// These symbols are optional and used to indicate the comments.
; Each C statement is terminate with the semicolon.
{} The braces are required in all C programs. They indicate the
beginning and the end of the program instruction.

Cout Function

The cout function is used to write information to standard output (normally your monitor).
It can be used to print numbers, string or characters. A typical structure of this function is

Cout<<"char string"<< variable;

Where the << symbol represents the insertor function. This function is used to insert
Characters or numbers in to the standard output stream. Function prototype for cout
Statement is in the iostream.h header file, so it must be include in to the program.
Example:
#include<iostream.h>
main()

{
cout<<2; // DISPLAY NUMBER.
cout<<”HELLO”; // DISPLAY STRING.
cout<<’a’; // DISPLAY CHARACTER.
}
VARIABLES

A variable is a named location that can hold various values. All variables must be declare
before they can be used. A variable's declaration serves one important purpose that it
tells the C compiler that you are giving an identity to the variable.

Data type Description

char: It is eight bit long and it is commonly used to hold a single character.

int: Integer may hold singed whole numbers (Numbers with no fractional part). It may
hold values in the range of -32768 to 32767.

float and double : Data type float and double hold signed floating point values, which
may have fractional component,The difference between float and double is that double
provides twice the precision as does float.

Example:
#include<iostream.h>
#include<iomanip.h>
main()
{
int number=100;
cout<<number<<endl;
cout<<sizeof(number); // sizeof() function is used for getting the size of variable
// in memory.
}

OUTPUT
100
2

cin Function:

the cin function allows your program to get user input from the keyboard. A typical
structure for this function is
cin>>variable;
where >> is extractor operator. It is used to extract information from the input stream.

Example:
// program that calculates the voltage by ohm's law

#include<iostream.h>
main()

{
Float vol,cur,res;
cout<<”enter the value of the current”;
cin>>cur;
cout<<”enter the value of the resistance”;
cin>>res;
vol=cur*res;
cout<<”voltage is “<<vol;
}

Lab Assignment

Question 1: Write a program that will compute the area of a circle. The user must
enter the radius of the circle. Use the following formula for area A = 3.14 R2
Question 2: Write a program that will solve for the power dissipation of a resistor when the
voltage across the resistor and the current in the resistor are known. The relationship for
power dissipation is: P=I x R
Where
P= Power dissipated
I= Resistor current
V= Resistor voltage

Question 3: Write a program that calculates the memory size of variable of different
data type? Before writing a code study the following example: You can find the no. of
bytes of int data type by the 'sizeof( )' function as

cout << "size of int in bytes = " << sizeof(int);


Explore the no. of bytes of the other data types using sizeof() finction.
main()
{
clrscr();
cout <<" size of int in bytes = "<<sizeof(int);
getche();
return (0);
}
Question 4: Develop the program that will convert the temperature from degree
Celsius to degree Fahrenheit. User input the temperature in Fahrenheit. The
relation is
F=9/5*C+32

Lab Solution
Q No 1
1. Code
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float area,radius;
cout << "Enter radius of circle\n";
cin >> radius;
area = 3.14*pow(radius,2);
cout << "Area of circle is " << area<<endl;
return 0;
}

Output:

Q No 2
2. Code
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float P,I,R;
cout << "Enter resistor current\n";
cin >> I;
cout << "Enter resistor voltage\n";
cin >> R;
P = pow(I,2) * R;
cout << "The power discipated is " << P << "Watt"<<endl;
return 0;
}

Output:
Q No 3
3. Code
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;

return 0;
}

Output:

Q No 4

1. Code
#include <iostream>

using namespace std;


int main()
{
float f=0,c=0;
cout << "Enter temprature in celcius\n";
cin >> c;
f = 1.8 * c + 32;
cout << "The temprature in faranhite is: "<<f<<endl;
return 0;
}

Output:
Lab No. 03

OBJECTIVE:3

Familiarization with different types of operators.

THEORY:

OPERATOR

Operators are the symbols that cause a program to do something on the variables.
Following are the operators which are commonly used in C language.

Arithmetic Operators:

There are five arithmetic operators in C. they are

Operator Purpose

+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after
integer division

The % operator some times to referred as modulus operator.

Increment and Decrement Operator:

C provides the unary increment operator (++), and the unary increment operator (--) for the
increment or decrement of one (l) from the variable. If increment or decrement operator is
placed before the variables, they are referred to as the pre increment or pre decrement
operator,
respectively. If increment or decrement operator are placed after the variable, they are
referred as the post increment or post decrement operators

Example
#include<iostream.h>
main(
{
int a=l;
cout<< ++a; // increment first then display.
cout<< a++; // first display then increment.
cout<< a;
cout<< --a; // decrement first then display
cout<< a--; // first display then decrement.
cout<< a;
} //Observe the output

Relational Operator:
There are four relational operators they are

Operator Meaning

< Less than


<= Less than or equal to.
> Greater than.
>= Greater than or equal.

Closely associated with the relational operators are the following two equality operators.

Operator Meaning

== Equal to
!= Not Equal to.

These six operators are used to form logical expression, which represents condition that is
either
true or false. Resulting expression will be of type integer, since true is represented by integer
value 1 and false is represented by value 0.

Example
#include<iostream.h>
main()
{
int a=1, b=2;
cout<<(a<b);
cout<<(a>b);
cout<<(++a = =b);
cout<<a<=b;
cout<<a>=b;
}
Observe the Output
Logical Operator:

C contains three logical operators, they are


Operators Meaning
&& And
|| OR
! Not

The logical operators act upon the operands that are themselves logical expressions. The net
effect is to combine the individual logical expressions into more complex conditions that are
either true or false. The result of logical and operation will be true only of all the expression
are true, where as the result of a logical or operator will be true if either expression will be
true. In other words, the result of logical or operation will be false When all expression Will be
false.

#include<iostream.h>
main()
{
int a=l , b=2;
cout<<( (a<b) && (a<=b));
cout<<((a= =b)) || (a<b));
cout<<( !(a= =b));
} //Observe the Output

Manipulators
Manipulators are operators used with the insertion operators to modify or manipulate the way
in
which data is displayed. The function prototype for the manipulators is the iomanip.h header
file.
Two of the most common manipulators are endl and setw(). endl is used for new line, Where
setw() is used setting the specific width.

Example
#include<iostream.h>
#include<iomanip.h>
main()
{
cout<<”MEHRAN’’<<setw(5)<<’’UNIVERSITY’’<<end<<’’JAMSHORO’’;
}

Observe how manipulators perform their function. Also search some other manipulators from
the
help & right down the function of at least three by taking suitable examples

Output or the above program:


MEHRAN UNIVERSITY
JAMSHORO
Lab Assignement
Question 1: Run the following program step-by-step using “F8 key" and see the output on
the output window. Observe that how the escape sequence works.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<”\a”;
cout<<”welcome to”;
cout<<”\b”;
cout<<”C”;
cout<<”\n”;
cout<<”welcome ”;
cout<<”\r”;
cout<<”to”;
cout<<”\t”;
cout<<”C”;
cout<<”\73\073\a”;
cout<<”\a welcome to \b C \n welcome\r to \tC”;

Question 2: Write a program which calculates the roots of Quadratic equation.

Where
X1= (-b+(b*b-4*a*c) / (2*a)
X2= (-b-(b*b-4*a*c) / (2*a)

Question 3: (a) Execute the following code step-by-step using "F8 key" and observe how
to integer variables are declared, initialized and modified in the program.

#include<iostream.h>
void main()
{
int i=0;
int j=1;
cout<<”i=”<<i<<”j=”<<j<<endl;
i=10;
j=20;
cout<<”i=”<<i<<”j=”<<j<<endl;
}
(b) In the above code change

int i=0;
int j=1;
to
const int i =0;
const int j =1;
now compile it and find out the errors, and try to understand the cause of the errors.

Question 4: Are the following expression are true or false.

1>2
‘a’<’b’
1==2
‘2’ = = ‘2’

Question 5: Rewrite the following statement using the unary operator. Also write a prog;
using modulo operator.

a=a+1
a=a -1
b+=1
b-=1
Lab Solution:
Question 1: Run the following program step-by-step using “F8 key" and see the output on
the output window. Observe that how the escape sequence works.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<”\a”;
cout<<”welcome to”;
cout<<”\b”;
cout<<”C”;
cout<<”\n”;
cout<<”welcome ”;
cout<<”\r”;
cout<<”to”;
cout<<”\t”;
cout<<”C”;
cout<<”\73\073\a”;
cout<<”\a welcome to \b C \n welcome\r to \tC”;

}
Output:

Question 2: Write a program which calculates the roots of Quadratic equation.


Where
X1= (-b+(b*b-4*a*c) / (2*a)
X2= (-b-(b*b-4*a*c) / (2*a)
Code
#include <iostream>
#include <cmath>
using namespace std;

int main() {

float a, b, c, first_root, second_root, disc, realPart, imag_part;


cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;
disc = b*b - 4*a*c;
if (disc > 0) {
first_root = (-b + sqrt(disc)) / (2*a);
second_root = (-b - sqrt(disc)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "first root = " << first_root << endl;
cout << "second root = " << second_root << endl;
}
else if (disc == 0) {
cout << "Roots are real and same." << endl;
first_root = -b/(2*a);
cout << "first root = second root =" << first_root << endl;
}

else {
realPart = -b/(2*a);
imag_part =sqrt(-disc)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "first root = " << realPart << "+" << imag_part << "i" << endl;
cout << "second root = " << realPart << "-" << imag_part << "i" << endl;
}

return 0;
}

Output:
Question 3: (a) Execute the following code step-by-step using "F8 key" and observe how
to integer variables are declared, initialized and modified in the program.

#include<iostream.h>
void main()
{
int i=0;
int j=1;
cout<<”i=”<<i<<”j=”<<j<<endl;
i=10;
j=20;
cout<<”i=”<<i<<”j=”<<j<<endl;
}

(b) In the above code change

int i=0;
int j=1;
to
const int i =0;
const int j =1;
now compile it and find out the errors, and try to understand the cause of the errors.
Ans:
The compiler gives a compilation error because we cannot change the value of Constants
during program execution as they are immutable. To get rid of this error we must not change
value of variables.
Question 4: Are the following expression are true or false.

1>2
‘a’<’b’
1==2
‘2’ = = ‘2’
Ans:
(i) 1 > 2
This statement is false.
(ii) ‘a’ < ‘b’
This statement is true.
(iii) 1==2
This statement is false.
(iv) ‘2’ == ‘2’
This statement is true.
Question 5: Rewrite the following statement using the unary operator. Also write a prog;
using modulo operator.

a=a+1
a=a -1
b+=1
b-=1
Code:
#include <iostream>
using namespace std;

int main()
{
int a=0,b=0;
cout << ++a << endl;
cout << --a << endl;
cout << ++b << endl;
cout << --b << endl;
return 0;
}
Output:

Q no 5(ii):
Code:
#include <iostream>
using namespace std;

int main()
{
int dividend, divisor , modulo;
cout << "Enter value of dividend\n";
cin >> dividend;
cout << "Enter value of divisor\n";
cin >> divisor;
modulo = dividend % divisor;
cout << "The modulo of " << dividend << " divided by " << divisor << " is " << modulo<<endl;
return 0;
}

Output:
Lab No. 04

OBJECTIVE:

a) To be familiar with if - else statement.


b) To be familiar with switch statement.
c) To be familiar conditional operator.

Theory:

The if else statement:

The if else statement is used to carry out a logical test and then take one of two possible
actions, depending on the outcome of the test (i.e., whether the outcome is true or false). The
else portion of the if else statement is optional. Thus in its simplest general form, the
Statement Can be written as

If (expression) Statement
The expression must be placed in the parenthesis. as shown above, In this form the
statement will be executed only if the expression has a nonzero value (i,e, if expression is
true If the expression has a value zero (i.e. if the expression is false then the statement be
ignored.

The general form of an If statement which include the else clause is


if (expression) statement1 else statement2

If the expression has a nonzero value (i.e. if expression is true), then statement will be
execute, otherwise statement2 will be execute.

Example

// A program for finding the smallest number


#include<iostream.h>
main()
{
int a =2 , b =3, small;
if(a<b)
small=a;
else
small=b;
cout<<small;}

The switch statement:

The switch statement causes a particular group of statements to be chosen from several
available groups. The selection is based upon the current value of an expression, which is
included within the switch statement.

The general form of the switch statement is

Switch (expression) statement

Where expression results in an integer value. Note that expression may also be of type char,
since individual character have equivalent integer values.
The embedded is generally a compound statement that specifies alternate courses of action.
Each alternate expressed as a group of one or more individual statement within the overall
embedded statement.
For each alternative, the first statement within the group must be preceded by one or more
case labels the case label identify the different group of the statement (I.e. the different
alternatives) and distinguish them from one another.

Example:

#include<iostream.h>
main( )
{
int a, b;
char c;
cout<<”enter first number”;
cin>>a;
cout<<”enter second number”;
cin>>b;
cout<<”enter your choice”<<endl;
cout<<” 1 – Addition"<<endl;
cout<<” 2 – Multiplication"<<endl;
cout<<” 3 – Subtraction"<<endl;
cout<<” 4 – Division"<<endl;
c=getche();
switch( c )
{
case
cout<<”sum is “<<a+b;
break;
case'2’:
cout<<”Multiplication is “<<a*b;
break;
case’3’:
cout<<”Subtraction is “<<a-b;
break;
case'4’;
cout<<”division is “<<a/b;
break;
default:
cout<<”incorrect choice”;}}

Note that each the groups is end with the break statement. The break statement cause
control to be transferred out of the switch statement, thus preventing more than group of
statement from being executed. one or the labeled groups of the statement within the switch
statement may be labeled default This group will be selected if none of the case labels
matches the value of the expression.

Conditional Operator:

Another decision maker in C is conditional operator. It is similar to if else statement. The


general from of the conditional operator is

Expression 1 ? Expression 2: expression 3

What happens is that when expression 1 is true, the whole operation becomes the value of
the expression 2, on the other hand if the expression 1 is false, the whole operation becomes
the value of expression3.

Example

#include<iostream.h>
main()
{
int a=2,b=3, small;
small= (a<b) ? a : b;
getch();
}

Lab Assignment
Question 1: Write a program that determines whether an integer is even or odd and negative
or positive. Make use of modulo operator.

Question 2: Write a Mark Sheet program that accepts the marks of the different subjects from
the user.

Calculate total marks, percentage and grade.


If per<60 and per >50 then Grade is “C"
If per<70 and per >60 then Grade is "B"
If per<80 and per>70 then Grade is "A"
If per>80 then Grade is "A-I"
If per<50 then prints FAIL.

Question 3: Write a program that finds the maximum number from three input numbers?

Question 4: Create a program in which the user selects name of the figure and program
presents the formula that is used for calculating its area. Use a rectangle, triangle, circle, and
parallelogram as the figure choice?
Lab Solution:
Question 1: Write a program that determines whether an integer is even or odd and
negative or positive. Make use of modulo operator.
Code:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer :";
cin >> n;
if (n>0)
{
cout << "Number is positive &";
if (n%2==0)
{
cout << "Number is even";
}
else{
cout << "Number is odd";
}
cout <<endl;
}
else if (n<0)
{
cout << "Number is negative &";
if (n%2==0)
{
cout << "Number is even";
}
else{
cout << "Number is odd";
}
cout<<endl;
}
else{
cout << "Number is zero\n";
}
return 0;
}

Output:

Question 2: Write a Mark Sheet program that accepts the marks of the different subjects from
the user.

Calculate total marks, percentage and grade.


If per<60 and per >50 then Grade is “C"
If per<70 and per >60 then Grade is "B"
If per<80 and per>70 then Grade is "A"
If per>80 then Grade is "A-I"
If per<50 then prints FAIL.
Code:
#include<iostream>
using namespace std;

int main()
{
int math,eng,phy, comp, total_marks, obtained_marks;
string grade;
float percentage;
cout << "Enter your mathmatics marks"<< endl;
cin >> math;
cout<<"Enter English marks"<<endl;
cin>>eng;
cout<<"Enter your Physics marks"<< endl;
cin >> phy;
cout << "Enter your Computer science marks"<<endl;
cin >> comp;
total_marks = 4 *100;
obtained_marks = math + comp + phy + eng;
percentage = (float(obtained_marks) / float(total_marks)) * 100;
if (obtained_marks <= total_marks)
{
if (percentage >= 50)
{
if (percentage <= 60 && percentage >=50)
{
grade = "C";
}
else if (percentage <= 70 && percentage >=60)
{
grade = "B";
}
else if (percentage <= 80 && percentage >=70)
{
grade = "A";
}
else
{
grade = "A+";
}
}
else{
cout << "You have been failed\n";
}
}
else{
cout << "You have eentered wrong data\n";
}
cout << "Your obtained marks are "<<obtained_marks<< "& your percentage is " << percentage << " & your grade is " << grade <<endl;

Output:

Question 3: Write a program that finds the maximum number from three input
numbers?
Code:
#include <iostream>
using namespace std;
int main()
{
int a,b,c,max;
cout << "Enter three numbers\n";
cin >> a >> b >>c;
max = a;
if (b>max)
{
max = b;
}
if (c>max)
{
max = c;
}
cout << "Maximum number is " << max<<endl;
return 0;
}

Output:

Question 4: Create a program in which the user selects name of the figure and
program presents the formula that is used for calculating its area. Use a rectangle,
triangle, circle, and parallelogram as the figure choice?
Code:
#include <iostream>
using namespace std;
int main()
{
int choice;
cout << "The program will teach you the formula for calculting area of your selected shape\n Please select an option\n";
cout << "1: Rectangle \n 2: Triangle \n 3: Circle \n 4: Parallelogram\n";
cin >> choice;
switch (choice)
{
case 1:
cout << "The formula for area of rectangle is \n area of rectangle = length x width\n";
break;
case 2:
cout << "The formula for area of triangle is \n area of triangle = 1/2(base x height)\n";
break;
case 3:
cout << "The formula for area of circle is \n area of circle = π x square of radius\n";
break;
case 1:
cout << "The formula for area of parallelogram is \n area of parallelogram = base x height\n";
break;
default:
cout<<"Your choice is invalid\n";
break;
}
return 0;
}

Output:

Lab No. 5
OBJECTIVE:
To be familiar with While loop.
To be familiar with Do-While loop.

Theory:

Loops: A loop is part of a program that repeats. Loops cause a section of your program to
be repeated a certain number of times. The repetition continues while a condition is true.
When the condition becomes false, the loop ends and control passes to the statements
following the loop.

There are three kinds of loops in C++: the for loop, the while loop, and the do loop.

While loops:
While loops are the simplest kind of loop. The basic structure is

while (condition ) { Code to execute while the condition is true }

In fact, a while loop is almost exactly like an if statement, except that the while loop causes
its body to be repeated. Just like an if statement, the condition is a Boolean expression. For
example, here's a while loop with two conditions:

while ( i == 2 || i == 3 )
Here’s a really basic example of a while loop:
while ( true )
{
cout << "I am looping\n";
}

Warning: if you run this loop, it will never stop! The condition will always evaluate to true.
This is called an infinite loop. Because an infinite loop never stops, you have to kill your
program to stop it (you can do this by either pressing Ctrl-C, Ctrl-Break or closing the
console window).

To avoid infinite loops, you should be sure your loop condition won’t always be true.

Example 1:

Let’s look at a loop that actually works well! Here’s a full program demonstrating while loops
by displaying the numbers from 0 to 9:

#include<iostream>
using namespace std;
int main()
{
int i = 0; // Don't forget to declare variables
while ( i < 10 ) // While i is less than 10
{
cout << i <<"\n";
i++; // Update i so the condition can be met eventually
}
}

Output:

0
1
2
3
4
5
6
7
8
9

The next example, ENDON0, asks the user to enter a series of numbers. When the number
entered is 0, the loop terminates. Notice that there’s no way for the program to know in
advance how many numbers will be typed before the 0 appears; that’s up to the user.

Example 2: // demonstrates WHILE loop

#include <iostream>
using namespace std;
int main()
{
int n = 99; // make sure n isn’t initialized to 0
while ( n != 0 ) // loop until n is 0 cin >> n; // read a number into n
cout << endl;
return 0;
}

Do-While loops:

Do-while loops are special-purpose and fairly rare. The main purpose of do-while loops is to make it easy to
write a loop body that happens at least once. The structure is

do
{ // body... }
while (condition);

The condition is tested at the end of the loop body instead of the beginning; therefore, the body of the loop will
be executed at least once before the condition is checked. If the condition is true, we jump back to the beginning
of the block and execute it again. A do-while loop is basically a reversed while loop. A while loop says, "Loop
while the condition is true, and execute this block of code", a do-while loop says, "Execute this block of code,
and then loop back while the condition is true".

Example 3:

Let’s look at a loop that actually works well! Here’s a full program demonstrating while loops by displaying the
numbers from 0 to 9:

#include <iostream> using namespace std; int main() {


int i = 1;
do{
cout<<i<<"\n"; i++;
} while (i <= 10) ;
}

Output:

1
2
3
4
5
6
7
8
9
10

Essentials of Counter-Controlled Repetition:

This section uses the while repetition statement to formalize the elements required to perform counter-
controlled repetition. Counter-controlled repetition requires

1. The name of a control variable (or loop counter)


2. The initial value of the control variable
3. The loop-continuation condition that tests for the final value of the control variable
4. (i.e., whether looping should continue)
5. The increment (or decrement) by which the control variable is modified each time
through the loop.

Lab Assignment:

1. With the help of while, Do-while loop generate following series:


i) Natural numbers from 1 to 100
ii) Even Numbers between 1 and 40
iii) Odd Numbers between 1 and 40

2. Write C++ statements to calculate sum of first 100 natural numbers.


3. Write a program that input 10 numbers from the user then prints how many of them were in the
range of 20 to 40 and how many were out of this range.
4. Write a program that takes input of integers repeatedly until user enters a negative number
then calculates and print the sum and average of all positive numbers.
5. Write C++ statements to calculate factorial of entered numbers.
6. Write C++ statements that prints access granted if username and password is correct,
otherwise ask user input again and again till the correct username and password entered.
Lab Solution:
With the help of while, Do-while loop generate following series:
Natural numbers from 1 to 100
Code:
#include <iostream>
using namespace std;
int main()
{
int n=1;
cout << "First 100 natural numbers are\n";
while (n<=100)
{
cout << n<<endl;
n++;
}
return 0;
}
Output:
Even Numbers between 1 and 40
code:
#include <iostream>
using namespace std;
int main()
{
int n=0;
cout << "First 100 natural numbers are\n";
while (n<=100)
{
cout << n<<endl;
n+=2;
}
return 0;
}

output:

Odd Numbers between 1 and 40


code:
#include <iostream>
using namespace std;
int main()
{
int n=1;
cout << "First 100 natural numbers are\n";
while (n<=100)
{
cout << n<<endl;
n+=2;
}
return 0;
}

output:

Question 2: Write C++ statements to calculate sum of first 100 natural numbers.
Code:
#include <iostream>
using namespace std;
int main()
{
int n=1;
cout << "First 100 natural numbers are\n";
while (n<=100)
{
sum+=n;
n++;
}
cout << "Sum of first 100 natural numbers is: ";
return 0;
}

Output:
Question 3: Write a program that input 10 numbers from the user then prints how many
of them were in the range of 20 to 40 and how many were out of this range.
Code:
#include <iostream>
using namespace std;
int main()
{
int num[10], range_1, range_2,i=0;
while (i<10)
{
cout<<"Enter number "<<i+1;
cin >>num[i];
}
while (n<10)
{
if (num[i]>=20 && num[i] <=40)
{
range_1++;
}
else{
range_2++;
}
}
cout << range_1<<" numbers are in range of 20 to 40\n";
cout << range_2<<" numbers are out of range\n";
return 0;
}

Output:

Question 4: Write a program that takes input of integers repeatedly until user enters a
negative number then calculates and print the sum and average of all positive
numbers.
Code:
#include <iostream>
using namespace std;
int main()
{
int num,sum=0,count;
float avg;
cout<<"Enter positive number\n";
cin >> num;
while (num>-1)
{
sum+=n;
count++;
cout<<"Enter positive number\n";
cin >> num;
}
cout<<"You enterd a negative number\n";
avg = float(sum) / float(count);
count << "Sum of numbers is: "<<sum<<endl;
count << "Average of numbers is: "<<avg<<endl;
return 0;
}

Output:

Question 5:Write C++ statements to calculate factorial of entered numbers.


Code:
#include <iostream>
using namespace std;
int main()
{
int num;
long long int factorial=1;
cout << "Enter a number for factorial\n";
cin >> num;
int i=num;
do
{
factorial*=i;
--i;
} while (i>0);
cout << "The factorial of number"<<num<<" is " << factorial<<endl;
return 0;
}

Output:
Question 6: Write C++ statements that prints access granted if username and password is correct,
otherwise ask user input again and again till the correct username and password entered.
Code:
#include <iostream>
using namespace std;
int main()
{
string username,password,correct_user = "USER", correct_password = "passwd";
cout << "Enter the username \n username is USER\n";
cin >> username;
cout << "Enter the password \n password is passwd\n";
cin >> password;
do
{
cout << "Enter the username \n username is USER\n";
cin >> username;
cout << "Enter the password \n password is passwd\n";
cin >> password;
if (username==correct_user && password==correct_password)
{
cout << "ACCESS GRANTED\N";
}
else{
cout<<"Please ente correct user & password\n";
}
} while (!(username==correct_user && password==correct_password));
}

Output:
Lab No. 6
OBJECTIVE:
To be familiar with For loop.
To be familiar with Nested loop.

Theory:

Loops: A loop is part of a program that repeats. Loops cause a section of your program to be
repeated a certain number of times. The repetition continues while a condition is true. When
the condition becomes false, the loop ends and control passes to the statements following the
loop.
There are three kinds of loops in C++: the for loop, the while loop, and the do loop.

For Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.

Syntax:

The syntax of a for loop in C++ is –

for ( init; condition; increment )


{
statement(s);
}

Like the while-loop, this loop repeats statement while condition is true. But, in addition, the for
loop provides specific locations to contain an initialization and an increase expression,
executed before the loop begins the first time, and after each iteration, respectively.
Therefore, it is especially useful to use counter variables as condition.

It works in the following way:

1. initialization is executed. Generally, this declares a counter variable, and sets it to


some initial value. This is executed a single time, at the beginning of the loop.
2. condition is checked. If it is true, the loop continues; otherwise, the loop ends,
and statement is skipped, going directly to step 5.
3. statement is executed. As usual, it can be either a single statement or a block enclosed
in curly braces { }.
4. increase is executed, and the loop gets back to step 2.
5. the loop ends: execution continues by the next statement after it.

Example:

// countdown using a for loop


#include <iostream>
using namespace std;

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

}
Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,

The three fields in a for-loop are optional. They can be left empty, but in all cases the
semicolon signs between them are required. For example, for (;n<10;) is a loop
without initialization  or increase (equivalent to a while-loop); and for (;n<10;++n) is a loop
with increase, but no initialization (maybe because the variable was already initialized before
the loop). A loop with no condition is equivalent to a loop with true as condition (i.e., an infinite
loop).

The continue statement


The continue statement causes the program to skip the rest of the loop in the current iteration,
as if the end of the statement block had been reached, causing it to jump to the start of the
following iteration. For example, let's skip number 5 in our countdown:

Example:

// continue loop example


#include <iostream>
using namespace std;

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

Output:

10, 9, 8, 7, 6, 4, 3, 2, 1,

The goto statement


goto allows to make an absolute jump to another point in the program. This unconditional
jump ignores nesting levels, and does not cause any automatic stack unwinding. Therefore, it
is a feature to use with care, and preferably within the same block of statements, especially in
the presence of local variables.

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 (:).

goto is generally deemed a low-level feature, with no particular use cases in modern higher-
level programming paradigms generally used with C++. But, just as an example, here is a
version of our countdown loop using goto:
Example:
// goto loop example
#include <iostream>
using namespace std;

int main ()
{
int n=10;
mylabel:
cout << n << ", ";
n--;
if (n>0) goto mylabel;
cout << "liftoff!\n";
}

Output:
10, 9, 8, 7, 6, 5, 4

Nested Loop:

Nested loop means a loop statement inside another loop statement. That is why nested
loops are also called as “loop inside loop“. C++ allows at least 256 levels of nesting.

Syntax for Nested For loop:

for ( initialization; condition; increment ) {


for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}

Syntax for Nested While loop:

while(condition) {
while (condition) {
// statement of inside loop
}
// statement of outer loop
}

Syntax for Nested Do-While loop:

do {
do {
// statement of inside loop
}
while (condition);
// statement of outer loop
}
while (condition);

Note:  There is no rule that a loop must be nested inside its own type. In fact, there can be
any type of loop nested inside any type and to any level.

Example
C++ program to print the number pattern.

1
12
123
1234
12345

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int i=1,j;
while (i <= 5)
{
j=1;
while (j <= i )
{
cout <<j;
j++;
}
cout << endl;
i++;
}
getch();
return 0;
}

In this program, nested while loop is used to print the pattern. The outermost loop runs 5
times and for every loop, the innermost loop runs i times which is 1 at first, meaning only “1” is
printed, then on the next loop it’s 2 numbers printing “1 2” and so on till 5 iterations of the loop
executes, printing “1 2 3 4 5”. This way, the given number pattern is printed.

Lab Assignment:
1. Find power of any number using for loop.
2. Write a program in C++ to calculate product of digits of any number.
3. Write a program in C++ to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) +
(5*5) + ... + (n*n).
4. Write a program in C++ to make such a pattern like right angle triangle using number which
will repeat the number for that row.
1
22
333
4444
55555
5. Write a program in C++ to display the pattern like a diamond.

*
***
*****
*******
*********
*******
*****
***
*
Lab Solution:
Question 1: Find power of any number using for loop.
Code:
#include <iostream>
using namespace std;
int main()
{
int exp,base;
long long int ans=1;
cout << "Enter base\n";
cin >> base;
cout << "Enter exponent\n";
cin >> exp;
for (int i = 0; i < exp; i++)
{
ans*=base;
}
cout << ans <<endl;
return 0;
}

Output:

Question 2: Write a program in C++ to calculate product of digits of any number.


Code:
#include <iostream>
using namespace std;
int main()
{
int n,temp;
long long int product=1;
cout << "Enter any number\n";
cin >> n;
for (;n>0;)
{
temp = n % 10;
product *= temp;
n = n / 10;
}
cout << "Product of digits of enterd number is " <<product<<endl;
return 0;
}

Output:

Question 3: Write a program in C++ to calculate the sum of the series (1*1) + (2*2) +
(3*3) + (4*4) + (5*5) + ... + (n*n).
Code:
#include <iostream>
using namespace std;
int main()
{
int n;
long long int series_ans=0;
cout << "Enter length of the series to be calculated\n";
cin >> n;
for (int i = 1; i <= n; i++)
{
series_ans += i*i;
}
cout << series_ans<<endl;
return 0;
}

Output:

Question 4: Write a program in C++ to make such a pattern like right angle triangle
using number which
will repeat the number for that row.
1
22
333
4444
55555
Code:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter any number to print pattern\n";
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < i; j++)
{
cout << i;
}
cout << endl;
}
return 0;
}
Output:

Question 5: Write a program in C++ to display the pattern like a diamond.


Code:
#include<iostream>
using namespace std;
int main()
{
int n, space = 1;
cout<<"Enter Number of Rows : ";
cin>>n;
space = n - 1;
for(int i = 1; i<=n; i++)
{
for (int j = 1; j<=space; j++)
cout<<" ";
space--;
for (int k = 1; k<= 2*i-1; k++)
cout<<"*";
cout<<"\n";
}
space = 1;
for(int i = 1; i<= n - 1; i++)
{
for (int j = 1; j<= space; j++)
cout<<" ";
space++;
for (int k = 1 ; k<= 2*(n-i)-1; k++)
cout<<"*";
cout<<"\n";
}
return 0;
}

Output:
Lab No. 07

OBJECTIVE:

a) To be familiar with Array


Theory:
Array: An array is a data structure, which can store a fixed-size collection of elements of the
same data type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type. The Memory Location in the
array are known as element of array. The total number of element in the array is called its
length.
Advantages and Uses of Arrays in C, C++
Arrays represent multiple data items of the same type using a single name.
In arrays, the elements can be accessed randomly by using the index number.
Arrays allocate memory in contiguous memory locations for all its elements. Hence, there is
no chance of extra memory being allocated in case of arrays. This avoids memory overflow or
shortage of memory in arrays.
Using arrays, other data structures like linked lists, stacks, queues, trees, graphs etc can be
implemented.
Two-dimensional arrays are used to represent matrices.
Declaring One-Dimensional Arrays:
Define:
The process of specifying array name, length and data type is called Array declaration.
Syntax:
Data_Type Identifier [Length];
The square bracket holds the number of elements in the array denoted by n.
Example:
int arr[10]

Array initialization: The process of assigning/storing elements to an array at the time of


array declaration is called Array initialization.
Note that the first element in an array is stored at index 0, while the last element is stored at
index n-1, where n is the total number of elements in the array.
Example:
int marks [5] = {70, 56, 82, 49, 60}
Accessing Individual elements of array:

1) Name of array
2) Index of element

Syntax: The syntax of accessing an individual element of an array as follows:

Array_Name[Index];

Array_Name: It indicates the name of array.


Index: It indicates the index of element to be accessed.

Example:

int marks(5);
marks[0] = 20;
marks[1] = 50;
marks[2] = 70;
marks[3] = 80;
marks[4] = 90;

Accessing Array Elements using Loops:

An easier and faster way of accessing array elements is using loops. The following example shows
how array elements can be accessed using for loop.

int marks[5];
for(int i=0; i<5; i++) marks[i] = i;

Input and Output Values of an Array:

The process of input and output with arrays is similiar to the input and output with simple variables.
The cin object is used to input values in the arrays. The cout object is used to display values of arrays.
However, the use of these objects with each individual elements becomes very time-consuming
because each elements is treated as a simple variable.

Loops are frequently used to input and output data in an array. The use of loops with arrays makes
the process of input and output faster and easier. It also reduces the code written for this purpose.

A program that inputs five integers from the user and stores them in an array then displays all values
in the array without using loops.

Example:

#include <iostream.h>
#include <conio.h>
void main()
{
int arr[5];
cout<<"Enter five integers: "<<endl;
cin>>arr[0];
cin>>arr1]:
cin>>arr[2];
cin>>arr[3];
cin>>arr[4];
cout<<"The values in array are: \n";
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
getch();
}

Searching in Array:

Sequential Search
Binary Search

Sequential Search:

Sequential search is also called linear search or serial search. It is simple way to search an array for
the desired value.

It follows the following steps:

1. Visit the first element of the array and compare its value with the required value.
2. If the value of array matches with the desired value, the search is complete.
3. If the value of array does not match, move to next element and repeat same process.

Example:

#include <iostream.h>
#include <conio.h>
void main()
{
int arr[10] = {10,20,30,40,50,60, 70, 80, 90, 100);
inti, n, loc = .1;
clrscr();
cout<<"Enter value to find;
cin>>n;
for(i=0; i<10; i++);
if(arr[i]==n)
loc=i;
if(loc==-1)
cout<<”Value not found in the array.";
else;
cout<<”Value found at index"<<loc;
getch();
}

Binary Search:

Binary search is a quicker method of searching for value in the array. Binary search is very quick but it
can only search on sorted array. It cannot be applied on an unsorted array.
1. It locates the middle element of array and compares with the search number.
2. If they are equal, search is successful and the index of middle element is returned.
3. If they are not equal, it reduces the search to half of the array,
4. If the search number is less than the middle element, it searches the first half of array.
Otherwise it searches the second half of the array. The process continues until the required
number is found or loop completes without successful search.

Sorting Arrays:
Sorting is a process of arranging the values of array in a particular order. An array can be sorted in
two orders:

Ascending Order: In ascending order, the smallest value is stored in the first element of array;
second value is stored in the second element and so on. The largest value is stored in the last.
Following figure shows an array sorted in ascending order.

12 25 33 37 48 57 86 92
Sorted array in descending order

Descending Sort: In descending order, the largest value is stored in first element of array; second
largest in second element and so on. The smallest value is stored in the last element.

86 87 40 37 33 25
Sorted array in descending order

Selection Sort:

Selection sort is a technique that sorts an array moves it to its proper position. Selection sort works as
follows:
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Sort the remainder of the list excluding the first value

Example: Write a program that gets five inputs from the user in an array in ascending order.

#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int arr(5), i,j, min, temp;
for(i=0; i<5; i++);
{
cout<<"Enter value:”;
cin>>arr[i];
}
cout<<"The original values in array:\n";
for(i=0; i<5; i++)
cout<arr[i]<<" “;

for(i=0; i<4; i++)


{
min=i;
for(j=i+1;j<5; j++)
if(arr[ j ]< arr[min])
min = j;
if(min !=i)
{
temp = arr[i]:
arr[i]= arr(min):
arr(min) = temp;
}
}
cout<<"\nThe sorted array:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<” “:
getch();
}

Two-Dimensional Arrays:

Two-dimensional array can be considered as a table that consists of rows and column. Each element
in 2-D array is referred with the help of two indexes. One index is used to indicate the row and the
second index indicates the column of the element.

Syntax

The syntax for declaring 2-D array is as follows:


Data_Type Identifier[Rows] [Cols];

Data Type: It indicates the data types of the values to be stored in the array.
Identifier: It indicates the name of the array.
Rows: It indicates the number of rows in the array. It must be a literal con symbolic constant
Cols: It indicates the number of columns in the array. It must be a literal

Example:
The following statement declares a 2-D array with four rows and three columns.
int Arr[4][3];

The statement declares a two-dimensional array. The total number of elements can be determined by
multiplying rows and column. It means that the above array contains twelve elements.

Accessing Individual Elements of 2-D Array:

The array name and indexes of row and column are used to access an individual element of 2-D
array. For example, the following statement will store 100 in the second column of first row in the
array:
Arr [0][1] = 100;

Entering Data in 2-D Arrays:

You can enter data in any element of the array by using the name of array and index of the element.
For example, the following statements enter data in the first row of a 2-D array.

Arr[0][0]=10 10 stored in first column of first row


Arr[0][1]=20 20 stored in second column of first row
Arr[0][2]=30 30 stored in third column of first row
Arr[0][0]=40 40 stored in first column of second row
Arr[1][1]=50 50 stored in second column of second row
Arr[1][2]=60 60 stored in third column of second row

Initializing 2-D Arrays:


The two dimensional arrays can also be initialized at the time of declaration process of initialization is
performed by assigning the initial values in braces separated by commas. The values of each row can
further be assigned in nested braces.

Some important points to initialize two-dimensional arrays are as follows:


The elements of each row are enclosed within braces and separated by commas.
All rows are enclosed within the braces.

For number arrays, if the values for all elements are not specified, the un-specified elements are
initialized by zero. In this case, at least one value must be given.

Example:
Arr[3][4) = [ {12,5, 22, 84},
{95, 3, 41, 59},
{77, 6, 53, 62} ];

Multidimensional Arrays:

Multidimensional array is also called as array of arrays. Multidimensional arrays are not limited to two
indices. Multidimensional arrays can have three, four or more dimensions. The amount of memory
needed for an array rapidly increases with each dimension.

The general syntax of declaring multidimensional array is as follows:

Data_Type arrayName [a] [b]……[n];

a , b and n are constant expression indicating the length of different dimensions of the Array.
int arr[10] [5] [7];

Accessing Multidimensional Arrays:

The syntax to access an element of a multidimensional array is as follows:


a , b and n are expression indicating the length of different dimensions of the Array.

arr[0][0][0] = 10;
arr[0][0][1] = 10;
aar[0][0][2] = 10:
arr[9][4][6] = 10;

Lab Assignment:
1. Can you declare an array without assigning the size of an array?
2. Write a program, to calculate the average of the marks of 10 students?
3. Write a program, to display first and last element of an array?
4. Write a program, to find the maximum and minimum value in array?
5. Write a program that will add two matrix of the same order?
Lab Solution:
Q no 1: Can you declare an array without assigning
the size of an array?
Ans : It is impossible to declare an array without giving
its size because if we do so we will get a segmentation
fault. But if we initialize the array with some values then
we don’t need to give size as compiler would
automatically count number of
elements. But for just declaration it is important to give
the size of array as it has to be allocated memory from
the stack.
Q no 2: Write a program, to calculate the average of
the marks of 10 students?
Code:
#include <iostream>
using namespace std;
int main()
{
int marks[10],sum=0;
float average;
for (int i = 0; i < 10; i++)
{
cout << "Enter marks of student "<<i+1<<endl;
cin >> marks[i];
}
for (int i = 0; i < 10; i++)
{
sum+=marks[i];
}
average = float(sum) / 10.0;
cout << "The average marks of each student is "<<average<<endl;
return 0;
}
Output:

no 3: Write a program, to display first and last element of an array?


Code:
#include <iostream>
using namespace std;
int main()
{
int num[10] = {22,99,90,89,56,67,43,29,20,11};
int n = sizeof(num) / sizeof(num[0]);
cout << "First element of array is "<<num[0]<<endl;
cout << "Last element of array is "<<num[n-1]<<endl;
return 0;
}

Output:

Q no 4: Write a program, to find the maximum and minimum value in array?


Code:
#include <iostream>
using namespace std;
void sorting(int arr[]){
int temp;
int n =10;
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-i; j++)
{
if (arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main()
{
int num[10] = {22,99,90,89,56,67,43,29,20,11};
int n = sizeof(num) / sizeof(num[0]);
sorting(num);
cout << "Minimum element in array is "<<num[0]<<endl;
cout << "Maximum element in array is "<<num[9]<<endl;
return 0;
}
Output:

no 5: Write a program that will add two matrix of the same order?
Code:
#include <iostream>
using namespace std;
int main()
{
int a[10][10] , b[10][10];
int c1,c2,r1,r2;
cout << "Enter number of rows & columns of both metrices \n";
cin >> r1 >> r2 >> c1 >> c2;
int c[r1][c1];
if(r1!=r2 || c1!=c2)
{
cout << "Addition is not possible";
exit (0);
}
else{
cout << "Enter elements of first matrix\n";
for (int i = 0; i < r1; ++i)
{
for (int j = 0; j < c1; ++j)
{
cin >> a[i][j];
}
}
cout << "Enter elements of second matrix\n";
for (int i = 0; i < r1; ++i)
{
for (int j = 0; j < c1; ++j)
{
cin >> b[i][j];
}
}
for (int i = 0; i < r1; ++i)
{
for (int j = 0; j < c1; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}
}
cout << "The new metrix after addition is \n";
for (int i = 0; i < r1; ++i)
{
for (int j = 0; j < c1; ++j)
{
cout << c[i][j] << "\t";
}
cout <<endl;
}
}
return 0;
}

Output:
Lab No. 08

OBJECTIVE:

a) To be familiar with Structures.

Theory:

Structures
A structure is a collection of multiple data types that can be referenced with a single name. It
may contain similar or different data types. The data items in a structure are called Structure
elements, members, or fields. The structures are used to join simple variables together to
form complex variables.
The difference between an array and a structure is thatan array consists of a set of variables
of the same data type. However, a structure may consist of different data types.
The structures are used to define new data types. The user can define a new data type at
may contain different types of data. A simple variable can store only one value at a time. But a
structure variable can store multiple values at the same time
Declaring a Structure
A structure is declared by using the keyword struct followed by the structure name. The
structure members are defined with their type inside the opening and closing braces. The
closing braces are ended with a semicolon. The declaration tells the compiler about the
details of the structure. The compiler does not allocate any memory.
The syntax for declaring a structure is as follows:
struct Struct_Name
{
Data Type1 Identifier1;
Data_Type2 Identifier2;
.
.
}
struct: It is the keyword that is used to declare a structure.
Struct Name: It is the name of the structure. The name of a structure is also known as a
structure tag. It can be any legal identifier.
Data_Type1: It indicates data types of the first member of the structure.
Identifier1: It indicates the name of the first member of the structure.
Data_Type2: It indicates data types of the second member of the structure.
Identifier2:It indicates the name of the second member of the structure
The structure declaration is terminated by a semicolon. The structure declaration is also
called a structure specifier.
Defining Structure Variable
The structure variable can be defined after the declaration of a structure. The process of
defining a structure variable is the same as defining a variable of basic types such as int and
char. The definition tells the compiler to allocate memory space for the variable. The compiler
automatically allocates sufficient memory according to the elements of the structure.
Syntax
The syntax of defining a structure variable is as follows:
Struct_NameIdentifier;
Struct_Name: is the name of the structure.
Identifier: is the name of the variable to be defined.
Example
Student Usman;
The above example defines a structure variable, Usman. The variable consists of four
members as specified in the structure declaration. The statement allocates the memory space
for all four members of the structure as follows:
The structure variable Usman will occupy 9 bytes in the memory. The member variable RollNo
occupies 2 bytes, Marks occupies 2 bytes, Average occupies 4 bytes and Grade occupies 1
byte. The total memory occupied by any variable of type Student will be 9 bytes.

Accessing Members of Structure Variable


Any member of a structure variable can be accessed by using the dot operator. The name of
the structure variable is written on the left side of the dot. The name of the member variable is
written on the right side of the dot. The dot operator is also known as the member access
operator.
Syntax The syntax of accessing a member of structure variable is as follows:
Struct_varMem_Var;
Struct_Var: is the name of the structure variable.
Mem_Var: is the name of the member variable to be accessed.
Example
Student Usman;
Usman. RollNo = 10;
Usman.Marks = 786:
Usman.Average = 89.52;
Usman.Grade = 'A';
The above example declares a structure variable Usman of type Student. It uses four
assignment statements to store different values in member variables of Usman. The dot
operator is used in each statement to access a separate member variable. The same method
can be used to input values in member variables and display these values as follows:
cin>>Usman. RollNo;
cin>>Usman.Marks;
cin>>Usman.Average;
cin>>Usman.Grade;
cout<<Usman.RollNo;
cout<<Usman.Marks;
cout<<Usman.Average;
cout<<Usman.Grade;
Program
Write a program that declares a structure to store Roll No, Marks, Average, and Grade of a
student. The program should define structure variable, inputs the values, and then displays
these values.
#include<iostream.>
#include<conio.h>
struct Student
{
int rno;
int marks;
float avg;
char grade;
}
void main()
{
clrscr();
Students;
cout<<"Enter roll no: ";
cin>>s.rno
cout<<"Enter marks: ";
cin>>s.marks;
cout<<"Enter average:";
cin>>s.avg;
cout<<"Enter grade:";
cin>>s.grade;
cout<<"You entered the following details: \n”;
cout<<"Roll No: "<<s.rno<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Average: "<<s.avg<<endl;
cout<<"Grade: "<<s.grade<<endl;
getch();
}

Initializing Structure Variables


The process of assigning values to member variables of structure is called the initialization of
structure variables. The assignment operator is used for initialization. The declaration of
structure variable is specified on the left side of an assignment operator. The values for
initialization are written on the right side of the assignment operator. The values are written in
braces. The values are written in the same sequence in which they are specified in the
structure declaration. Each value is separated by a comma. Syntax
The syntax for initializing structure variables is as follows:
Struct_Name Identifier = (Value 1, Value2...);
Struct_Name: It is the name of the structure.
Identifier: It is the name of the structure variable.
Value1, Value2 These are the values that are used to initialize the structure variable.
Example
Student Usman = 786. 89.52, 'A');
The above example declares a structure variable Usman of type Student. It initializes the
structure variable with the values written in braces on the right side of the assignment
operator.
Program
Write a program that declares a structure to store employee id and salary of an employee. It
defines and initializes a structure variable and displays it.
#include <iostream.h>
#include <conio.h>
struct emp
{
int eid;
int sal;
};
void main()
{
clrscr();
emp e = (20, 18500);
cout<<”Employee ID: <<e.eid<<endl;
cout<”Salary: <<e.sal<<endl;
getch();
}

Array as Member of Structure


A structure may consist of different types of data. The member variables can be simple data
types such as int, char, and float. The member variables can also be complex like arrays.
Example
struct Student
{
int RolNo:
int Marks[5]:
}

The above example declares a structure Student with two members. The first member is a
simple variable of type int, the second members an array of integers. It can be used to store
the marks of five subjects.
The array stored in a structure can e accessed by using both the dot operator and index The
dot operator is used to refer to the array. The index is used to access the individual elements
of the array as follows:
Student Usman:
Usman.RollNo=10;
Usman Marks[0] =89;
Usman.Marks[1] = 93;
Usman.Marks[2] =83;
Usman.Marks[3] = 79
Usman.Marks[4]= 95;
Initializing a Structure with Array as Member
The structure that contains an array as a member variable can be initialized in the same way
as initializing a simple structure variable. The values are written in braces and each value is
separated by a comma. Additionally, the values for the member array are written in nested
braces. The following example initializes the structure variable Usman:
Student Usman = {10 (89, 83, 81 79,95)};
Array of Structures
An array is a collection of the same type of data. An array can be of simple data type such as
int, char or float, etc. Similarly, an array can be of a user-defined type such as a structure. An
array of structures is a type of array in which each element contains a complete structure. It
can be used to store many records.

Example
struct Book
{
int BookID;
int Pages; float Price;
}
Book b[3];

The above example declares a structure Book. It defines an array of structures b[3]. The array
can store the records of three books.
The array is accessed by using its index. The structure is accessed by using dot operator. An
array of structures can be accessed as follows;
b[0].BookID = 1;
b[0].Pages = 230;
b[0].Price = 125;
Initializing Array of Structures
An array of structures can be initialized at the time of declaration by writing the values in
braces. The values for each element of the array are written in separate inner braces.
Example
struct Book
{
int BookID;
int Pages;
float Price;
};
Book b[3] = {{1,230,125.50),(2,480, 185.75},{3,360,145.50}};

The above example declares an array of structures and initializes it. The values are written in
braces. Each inner brace is used to initialize one element of the array
Lab Assignment
1. What is the main difference between array and structure?
2. Write a code required to define a structure for the following type of data:
a. Time(hours, minutes, seconds)
b. Date(Name of month, Day, Year)
3. Write a C++ program to assign data to members of a structure variable and display it.

4. Rewrite the following program after removing the syntactical errors (if any). Underline
each correction.

struct Pixels
{
            int color, style;
}

void showPoint(Pixels P)
{
            cout << P.color, P.style << endl;
}

int main()
{
            Pixels Point1 = (5, 3);
            showPoint(Point1);
            Pixels Point2 = Point1;
            color.Point1 += 2;
            showPoint(Point2);

            return 0;
}

5. An array stores details of 10 students (rollno, name, and marks in five subjects). Write
a program to create such an array and print out a list of students who have failed in
any subject.
Lab Solution:
Q no 1: Can you declare an array without assigning the size of an array?
Ans :
Arrays Structures
Array refers to a collection consisting of Structure refers to a collection consisting of
elements of same data type. elements of different data type.
Array uses subscripts or “[ ]” (square bracket) Structure uses “.” (Dot operator) for element
for element access. access.
Array size is fixed and is basically the number Structure size is not fixed as each element of
of elements multiplied by the size of an element. Structure can be of different type and size.
Array declaration is done simply using [] and Structure declaration is done with the help of
not any keyword. “struct” keyword.

Q no 2: Write a code required to define a structure for the following type of data:
a. Time(hours, minutes, seconds)
b. Date(Name of month, Day, Year)
Code:
#include <iostream>
using namespace std;
struct tim{
int hour;
int minute;
int second;
}t;
struct date{
string day;
int year;
string month;
}d;
int main()
{
date d;
tim t;
cout << "Enter the hour\n";
cin >> t.hour;
cout << "Enter the minutes\n";
cin >> t.minute;
cout << "Enter the second\n";
cin >> t.second;
cout << "Enter the name of month\n";
cin >> d.month;
cout << "Enter the name of day\n";
cin >> d.day;
cout << "Enter the year\n";
cin >> d.year;
cout << "The t now is " << t.hour << ":" << t.minute << ":" << t.second <<endl;
cout << "The month is " << d.month << " day is " << d.day << " year is " << d.year<<endl;
return 0;
}
Output:
Q
no
3:

Write a C++ program to assign data to members of a structure variable and display it.
Code:
#include <iostream>
using namespace std;
struct student{
int roll;
int age;
int marks;
};

int main()
{
student data;
data = {222,16,298};
cout<<"Roll = "<<data.roll<<"\n";
cout<<"Age = "<<data.age<<"\n";
cout<<"Marks = "<<data.marks;
return 0;
}
Output:

Q
no
4:

Rewrite the following program after removing the syntactical errors (if any). Underline each
correction.
Ans:

Q no 5: An array stores details of 10 students (rollno, name, and marks in five subjects).
Write a program to create such an array and print out a list of students who have failed in any
subject.
Code:
#include<iostream>
using namespace std;
struct student
{
int roll;
string name;
int sub1,sub2,sub3,sub4,sub5;
};
int main()
{
student s[10];
for(int i =0 ; i < 10 ; i++)
{
cout << "\n Enter Roll no : ";
cin >> s[i].roll;
cin.ignore();
cout << "\n Enter Name : ";
getline(cin,s[i].name);

cout << "\n Enter marks of five subjects. remember total marks are 100 :";
cin >> s[i].sub1 >> s[i].sub2 >> s[i].sub3 >> s[i].sub4 >> s[i].sub5;

}
cout<< "\n Students FAILED 1 SUBJECT \n ";
for(int i =0 ; i < 10 ; i++)
{
if(s[i].sub1 < 40 || s[i].sub2 < 40 ||s[i].sub3 < 40 ||s[i].sub4 < 40 ||s[i].sub5 < 40);
cout << s[i].roll << "\t" << s[i].name << "\n";
}

cout<< "\n Students FAILED IN MORE THAN 1 SUBJECT \n ";


for(int i =0 ; i < 10 ; i++)
{
if(( s[i].sub1< 40 && s[i].sub2 < 40) || (s[i].sub2 < 40 && s[i].sub3 < 40) || ( s[i].sub1 < 40 && s[i].sub3 < 40) || ( s[i].sub4 < 40 &&
s[i].sub5 < 40) || ( s[i].sub1 < 40 && s[i].sub5 < 40) || ( s[i].sub2 < 40 && s[i].sub5 < 40) || ( s[i].sub3 < 40 && s[i].sub3 < 40));
cout << s[i].roll << "\t" << s[i].name << "\n";
}
return 0;
}

Output:
Lab No. 09

OBJECTIVE:

a) To be familiar with Functions

Theory:

Function:
A function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions. ... A function declaration tells the compiler about a function's name, return type, and
parameters

Example:
A function is block of code which is used to perform a particular task, for example let's
say you are writing a large C++ program and in that program you want to do a particular task
several number of times, like displaying value from 1 to 10, in order to do that you have to
write few lines of code and you need to

Types of Function:
 User-Defined Functions
 Built-in Functions

Function Declaration:
 Function name.
 Function return type.
 Number and types of parameters.

Syntax:
Return-type Function-name(parameters);
Function Definition:
A set of statements that explain what a function does is called function definition.
It consists of two parts:
 Function Header
 Function Body

Syntax:
Return-type Function-name(parameters);
{
Statement 1;
Statement 2;
:
:
Statement N;
}
Example:
// Function declaration
void myFunction();

// The main method


int main() {
  myFunction();  // call the function
  return 0;
}

// Function definition
void myFunction() {
  cout << "I just got executed!";
}

Function Call:
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately. int max(int, int); Function
declaration is required when you define a function in one source file and you call that function
in another file.

Example:

#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}

int main() {

// calling the function


greet();

return 0;
}

Passing Parameters to function:


 pass by value
 pass by reference
Example of pass by reference:
void swapNums(int &x, int &y) {
  int z = x;
  x = y;
  y = z;
}

int main() {
int firstNum = 10;
int secondNum = 20;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";

  // Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);

  cout << "After swap: " << "\n";


  cout << firstNum << secondNum << "\n";

  return 0;
}

Example of Pass by value:


#include <iostream>
 
void foo(int y)
{
    std::cout << "y = " << y << '\n';
}
 
int  main()
{
    foo(5); // first call
 
    int  x{ 6 };
    foo(x); // second call
    foo(x+1); // third call
 
    return 0;
}

Return Values:
The specific value returned from a function is called the return value. When the return
statement is executed, the return value is copied from the function back to the caller. This
process is called return by value. Execution starts at the top of main
Example:
int myFunction(int x) {
  return 5 + x;
}

int main() {
  cout << myFunction(3);
  return 0;
}

// Outputs 8 (5 + 3)

What is a Variable?

Variable is a name assign to a storage area that the program can manipulate. A variable type
determines the size and layout of the variable's memory.

It also determines the range of values which need to be stored inside that memory and nature
of operations that can be applied to that variable.

Types of variable:
 Local variable
 Global variable

Local Variable

Local Variable is defined as a type of variable declared within programming block or


subroutines. It can only be used inside the subroutine or code block in which it is declared.
The local variable exists until the block of the function is under execution. After that, it will be
destroyed automatically.

Example of Local Variable

public int add(){


int a =4;
int b=5;
return a+b;
}

Global Variable

A Global Variable in the program is a variable defined outside the subroutine or function. It
has a global scope means it holds its value throughout the lifetime of the program. Hence, it
can be accessed throughout the program by any function defined within the program, unless it
is shadowed.

Example:

int a =4;
int b=5;
public int add(){
return a+b;
}

Register variable:

The register keyword is a request to the compiler that the specified variable is to be stored in


a register of the processor instead of memory as a way to gain speed, mostly because it will
be heavily used. The compiler may ignore the request.

Syntax:

Register data-type variable-name;

Example:

Register int n;

Function and Arrays:


An array can be passed to a function as parameters. When array is passed as parameters to
a function, only the address of first element of the array is passed. An array is passed by
reference not by value. A separate copy of array is not created in the function.
Syntax:
Return-type function-name(parameters[]);
Example: Void display(int[]);
Example: Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students
#include <iostream>
using namespace std;

// declare function to display marks


// take a 1d array as parameter
void display(int m[5]) {
cout << "Displaying marks: " << endl;

// display array elements


for (int i = 0; i < 5; ++i) {
cout << "Student " << i + 1 << ": " << m[i] << endl;
}
}
int main() {
// declare and initialize an array
int marks[5] = {88, 76, 90, 61, 69};

// call display function


// pass array as argument
display(marks);
return 0;
}

Lab Assignment:
1. Write a function addXY(x,y) to print the sum of two numbers entered by user.
2. Define two functions to print the maximum and the minimum number respectively among three
numbers entered by user.
3. Write a function that returns a string with your name repeated 10 times.
4. What will be the output of the following C++ code?

#include <iostream>
using namespace std;
void copy (int& a, int& b, int& c)
{
a *= 2;
b *= 2;
c *= 2;
}
int main ()
{
int x = 1, y = 3, z = 7;
copy (x, y, z);
cout << "x =" << x << ", y =" << y << ", z =" << z;
return 0;
}

5. Display Sum and Average of Array Elements Using for Loop.


Lab Solution:
Q no 1: Write a function addXY(x,y) to print the sum of two numbers entered
by user.
Code:
#include <iostream>
using namespace std;
void addxy(){
int x,y;
cout << "Enter two number for getting sum\n";
cin >> x >> y;
int sum = x + y;
cout << "Sum of x & y is: "<<sum<<endl;
}
int main()
{
addxy();
return 0;
}

Output:

Q no 2: Define two functions to print the maximum and the minimum number
respectively among three numbers entered by user.
Code:
#include <iostream>
using namespace std;
void minimum(int x,int y,int z){
int min=x;
if (min>y)
{
min = y;
}
if (min>z)
{
min = z;
}
cout << "Mnimum number is: "<<min<<endl;
}
void maximum(int x,int y,int z){
int max=x;
if (max<y)
{
max = y;
}
if (max<z)
{
max = z;
}
cout << "Maximum number is: "<<max<<endl;
}
int main()
{
int a,b,c;
cout << "Enter three numbers\n";
cin >> a >> b >>c;
minimum(a,b,c);
maximum(a,b,c);
return 0;
}

Output:

Q no 3: Write a function that returns a string with your name repeated 10


times.
Code:
#include <iostream>
using namespace std;
void name(){
string temp;
cout<<"Enter your name\n";
getline(cin,temp);
int i=0;
while (i<10)
{
cout<<"Your Name is "<<temp<<endl;
i++;
}
}
int main()
{
name();
return 0;
}

Output:
Q no 4: What will be the output of the following C++ code?
Code:
#include <iostream>
using namespace std;
void copy (int& a, int& b, int& c)
{
a *= 2;
b *= 2;
c *= 2;
}
int main ()
{
int x = 1, y = 3, z = 7;
copy (x, y, z);
cout << "x =" << x << ", y =" << y << ", z =" << z;
return 0;
}
Output:

Q no 5: Display Sum and Average of Array Elements Using for Loop.


Code:
#include <iostream>
using namespace std;
void sum_avg(int arr[]){
int sum=0;
float avg;
for (int i = 0; i < 5; i++)
{
sum+=arr[i];
}
avg = float(sum) / 5.0;
cout << "Sum of array elements is: "<<sum<<endl;
cout << "Average of array elements is: "<<avg<<endl;
}
int main()
{
int num[5];
for (int i = 0; i < 5; i++)
{
cout<<"Enter element "<<i+1<<endl;
cin >> num[i];
}
sum_avg(num);
return 0;
}

Output:
Lab No. 10

OBJECTIVE:
a) To be familiar with Strings.

Theory:

String
A collection of characters written in double quotations is called string or string constant. It may
consist of any alphabetic characters, digits, and special symbols.
A string is stored as an array of characters. The array is terminated by a special symbol
known as the null character. It is denoted by the escape sequence 10 and is used to indicate
the end of the string. It consists of backslash and zero.
The values stored in an array of characters can be manipulated individually using the index of
the array. The user can input, process, and displays the individual characters of a string in the
same way as an array.
Examples
Some examples of stings are as follows:
"Pakistan" "123" "99-Mall Road, Lahore"
String Declaration
C++ stores a string as an array of characters. An array is a group of contiguous memory
locations that can store the same type of data.
Syntax
The syntax of declaring a string in C++ is as follows:
char array_name [length];
char: It indicates the type of array used as a string.
array_name: It indicates the name of an array.
Length: It indicates the number of memory locations in the array.
Example
An example of string declaration is as follows:
char book [20];
The above statement declares a variable book. The value 20 in brackets indicates the length
of the string that can be stored in the variable. The above declaration allocates twenty
memory locations and each memory location can store one
String Initialization
The syntax of initializing a string in C++ is as follows:
chararray_name [length] = value;
char: It indicates the type of array used as a string.
array_name: It indicates the name of an array.
length: It indicates the number of memory locations in the array.
value: It indicates the value initialized in string. It is enclosed in double-quotes.
Example
The string variable can be initialized with a string value as follows:
char book[20] = "OOP using C++";
The above statement will store the string. The last character \0 in the memory is known as the
null character. It consists of backslash and zero. It indicates the end of the string. It is added
at the end of the string automatically. A string variable can also be declared without indicating
the length as follows:
char name = "Pakistan”;
The above statement automatically declares a string according to the length of the value.
Array of Strings
An array of strings is a two-dimensional array of characters. Each row of the array represents
one string. Each character in an array of strings is stored in a separate index of a two-
dimensional array
Syntax
The syntax of declaring an array of strings is as follows:
char str[rows][cols];
str: It indicates the name of a two-dimensional array.
rows: It indicates the number of rows in the array.
cols: It indicates the number of columns in each row of the array.
Example
char names[3][50];
The above example declares a two-dimensional array of characters with three rows and fifty
columns in each row. It can be considered as an array of three strings.
Initializing Array of Strings
An array of strings can be initialized in different ways. It can be initialized by assigning
individual characters to each index in the array. It can also be initialized by assigning
complete strings to each row in the array.
Example
The following example initializes an array of strings by assigning individual characters.
char str(3][5] = {'a': 'b', 'c': 'd', 'e',
‘f’, 'g'. 'h', ‘I’, ‘j’,
‘k’, ‘l’, 'm’, 'n', 'o' };
The above example declares a two-dimensional array of characters and initializes it with the
given values.
String Handling Functions (string.h)
The header file 'string.h' contains the built-in function that is used to process string values.
Some important function defined in this header file is as follows:
1. Strcmp()

The strcmp() function is used to compare two strings character by character. The comparison
is case-sensitive. It returns integer value as follows:
Less than zero: It returns a value less than zero if the first string is less than the second
string.
Zero: It returns zero if the first string is equal to the second string.
Greater than zero: It returns a value greater than zero if the first string is greater than the
second string.
Syntax
strcmp(str1, str2);
strcmp: It is the name of the function.
str1: It indicates the first string in comparison.
str2: It indicates the second string in comparison.
2. strcpy()
The word 'strcpy’ stands for string copy. The function is used to copy one string to another
including the terminating null character.
Syntax
strcpy(str1, str2);
strcpy: It is the name of the function.
str1: It indicates the first string in which the string value is to be copied.
str2: It indicates the second string whose value is to be copied. It can be a string variable or
string constant.
3. strlen()

The word 'strlen’ stands for string length. The function is used to find the length of a string.
The length includes all characters as well spaces in the string. It does not count the null
character. It returns an integer value indicating the length of the string.
Syntax
strlen(str);
strlen: It is the name of the function.
str: It indicates the string whose length is to be found.
4. strcat()

The strcat() function is used to append a copy of one string to the end of second string, It also
terminates the resulting string with null character. The string in which the value is copied
should have enough space to hold the result.
Syntax
strcat(str1, str2);
strcat: It is the name of the function.
str1: It indicates the name of the string in which the value is to be appended.
str2:It indicates the name of the string whose value is to be appended to str1.
5. strrev()

The strrev() function is used to reverse the specified string.

Lab Assignment:
1. Write a C++ program that reads three strings and prints the longest and smallest
string.
2. Write a program to count the number of words in a string as well as the number of
characters other than a space.
3. C++ Program to Compare Two Strings without using strcmp.

Lab Solution:
Q no 1: Write a C++ program that reads three strings
and prints the longest and smallest string.
Code:
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
string s1,s2,s3;
string smallest, longest;
int len1,len2,len3;
cout<<"Enter a string\n";
getline(cin,s1);
cout<<"Enter a 2nd string\n";
getline(cin,s2);
cout<<"Enter another string\n";
getline(cin,s3);
len1 = s1.size();
len2 = s2.size();
len3 = s3.size();
if (len1>len2 && len1>len3)
{
longest = s1;
if (len2<len3)
{
smallest = s2;
}
else{
smallest = s3;
}
}
else if (len2>len1 && len2>len3)
{
longest = s2;
if (len1<len3)
{
smallest = s1;
}
else{
smallest = s3;
}
}
else{
longest = s3;
if (len1<len2)
{
smallest = s1;
}
else{
smallest = s2;
}
}
cout << "Longest string is " << longest<<endl;
cout << "Smallest string is "<< smallest<<endl;
return 0;
}

Output:

Q no 2: Write a program to count the number of words in a string as well as


the number of characters other than a space.
Code:
#include <iostream>
using namespace std;
int main()
{
string sentence;
int words=0,spaces=0;
cout << "Enter a sentence\n";
getline(cin,sentence);
for (int i = 0; sentence[i]!='\0'; i++)
{
if (sentence[i]==' ')
{
spaces++;
}
}
cout << "The word count is " << spaces+1<<endl;
cout << "The character count is " << sentence.size()-spaces<<endl;
return 0;
}
Output:

Q no 3: C++ Program to Compare Two Strings without


using strcmp.
Code:
#include <iostream>
using namespace std;
int main()
{
string s1 = "This is Alpha 42";
string s2 = "This is alpha 42";
if (s1==s2)
{
cout << "Strings are equal\n";
}
else{
cout << "Strings are differnt\n";
}
return 0;
}

Output:
Lab No. 11

OBJECTIVE:
a) To be familiar with Pointers.

Theory:

Pointers
A pointer is a variable that is used to store a memory address. The reference operator is used
to access the memory address of a variable and store it in a pointer
Pointer Declaration
The method of declaring a pointer is the same as declaring a simple variable. An asterisk is
used in the declaration that indicates that the variable is a pointer variable.
Syntax
The syntax of declaring a pointer is as follows:
DataType *var
DataType: It is the type of variable pointed by the pointer variable
*: It indicates that the variable is a pointer variable var
Var:It is the name of the pointer variable.
Example
int *p;
The above statement declares a pointer variable p. The data type int indicates that it can
store the memory address of an integer variable. The data type of a pointer must be the same
as the data type of the variable whose memory address is to be stored in the pointer.
It is also possible to declare many pointer variables in one statement as follows:
float *p1, "p2;
The 'void' Pointer
The type of pointer variable and the type of variable it refers must be the same. It restricts the
use of a pointer variable to a specific type of variable. A pointer variable can store the address
of any type of variable if it is declared as void.
The keyword 'void' is used as the data type of the pointer as follows:
void *p;
The above statement declares a pointer variable p. The data type of the pointer is void. It
means that it can store the memory address of any type of variables
Example
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int n = 10;
float f = 25.18;
char c = ‘$’;
void *ptr;
ptr = &n;
cout<<"The value of n: "<<n<<endl;
cout<<"The address of n: "<<ptr<<endl;
ptr = &f;
cout<<"The value of f: "<<f<<endl;
cout<<"The address of f: "<<ptr<<endl;
ptr = &c;
cout<<"The value of c: "<<c<<endl;
cout<<"The address of c: "<<ptr<<endl;
getch();
}

Dereference Operator
The dereference operator is used to access the value of the variable whose memory address
is stored in the pointer. It is denoted by asterisk '*'. It is also called the indirection operator. It
can also be used to input a value in the variable and process the data stored in the variable.
Example
#include <iostream.h>
#include <conio.h>
void main()
{
cIrscr();
int a, b, s, *p1, *p2;
p1 = &a;
p2 = 8b;
cout<<"Enter an integer: ";
cin>>*pi;
cout<<"Enter an integer: ";
cin>>*p2;
s = *p1 + *02;
cou<<"*p1<<" + "<<*p2<<" "<<s<<endl;
getch();
}

Pointer Initialization
The process of assigning a memory address to a pointer at the time of declaration is called
point initialization. C++ does not initialize variables automatically. Therefore, a pointer variable
should be initialized so that it may not point to anything invalid.The pointer can be initialized to
any valid memory address. It can also be initialized to a NULL or 0 value.
Syntax
The syntax to initialize pointers is as follows:
DataType *P = &Variable;
DataType: It is the type of variable pointed by the pointer variable.
*P:It indicates that the pointer variable is to be initialized.
&: It is the address operator that is used to access the memory address of a variable.
Variable: It is the name of sthevariable whose memory address is assigned to the pointer.
Example
int n = 100;
int "p1 = &n;
int *p2 = NULL;
The pointer p1 is initialized to the memory address of variable n. The pointer p2 is initialized
to NULL.

Lab Assignment:
1. Given the following declarations:

char c;
double d;
char *pc;
double* pd;

Indicate & explain whether the following statements are correct or incorrect?
a. c=C;
b. pc=&c;
c. d=23.9;
d. pd=&d;

2. What will be the output of following program

#include <iostream.h>
#include <conio.h>
void main()
{
cIrscr();
int a=10, b=20, *c, *d;
c = &a;
d = &b;
cout<<a<<b<<endl;
cout<<c<<d<<endl;
cout<<*c<<*d<<endl;
}

Lab Solution:
Q no 1: Given the following declarations:
char c;
double d;
char *pc;
double* pd;
Indicate & explain whether the following statements are
correct or incorrect?
(i) c=C;
This statement is false as we have to use single quotes while
assigning value to a character variable.
(ii) pc=&c;
Yes this expression is correct as this is proper way to assign
memory address to a pointer.
(iii) d=23.9;
Yes this expression is also correct as this is how we assign
values to float variables.
(iv) pd=&d;
Yes this expression is correct as this is proper way to assign
memory address to a pointer.
Q no 2: What will be the output of following program
Code:
#include <iostream.h>
#include <conio.h>
void main()
{
cIrscr();
int a=10, b=20, *c, *d;
c = &a;
d = &b;
cout<<a<<b<<endl;
cout<<c<<d<<endl;
cout<<*c<<*d<<endl;
}
Output:
Lab No. 12

OBJECTIVE:
a) To be familiar with C++ Built-in functions.

Theory:

Built-in Functions
A type of function that is available as a part of language is known as a built-in function or
library function. These functions are ready-made programs. These functions are stored in
different header files. Built-in functions make programming faster and easier. C++ language
provides many built-in functions to solve different problems.
Different built-in functions are defined in different header files. Bult-in functions can be
accessed in programs by including the header files in which these functions are defined.
The 'conio.h' Header File
The word 'conio’ stands for console input/output. The header file 'conio.h’ contains the built-in
function that is used for input and output. Some important functions defined in this header file
are as follows:
clrscr()
The word 'clrscr' stands for the clear screen. The function is used to clear the contents of the
screen. When this function is executed, the screen is cleared and the cursor moves to the
start of the first-line on the screen.
Syntax:
clrscr();

getch()
The word 'getch’ stands for get character. The function is used to inputa single character from
the keyboard. The character typed by the user does not appear on the screen. It can be
stored in a variable by using an assignment statement. The user does not need to press Enter
key to complete the input. The function is frequently used to pause program execution.
Syntax:
variable = getch();
The use of variable is optional.
Example
#include <iostream.h>
#include <conio.h>
void main()
{
char ch;
cout<<"Enter any character ";
ch = getch();
cout<<"You entered "<<ch;
getch();
}

The above example inputs a character in variable ch by using getch() function and displays
the character. The last statement again uses getch() function to pause the program execution.
The user can see the output and then press any key to end the program.
getche()
The word ‘getche’ stands for get character echo. The function is used to input a single
character from the keyboard. The character typed by the user also appears on the screen. It
can be stored in a variable by using an assignment statement. The user does not need to
press Enter key to complete the input.
Syntax:
variable = getche();
The use of variable is optional.
getchar()
The word 'getchar' stands for get character. The function works similar to getch() and getche()
functions of ‘conio.h’ header file. It is used to input a single character from the keyboard. The
character can be stored in a variable by using an assignment statement. The user needs to
press Enter key to complete input. The character typed by the user also appears on the
screen.
Syntax:
variable = getchar();
The use of variable is optional.
putchar()
The word 'putchar' stands for put character. The function is used to display a single character
on the screen.
Syntax:
putchar(ch);
The 'parameter ch is the variable or constant whose value is to be displayed on screen.
Example
#include <iostream.h>
#include <conio.h>
void main()
{
char ch;
cout<<"Enter a character";
cin>>ch;
putchar(ch);
putchar(‘*’);
}

gets()
The word 'gets' stands for get string. The function is used to input a string value from the
keyboard. The value entered by the user can be stored in an array of characters. The string
may consist of any characters and space.
The user also needs to press Enter key after typing the string to complete the input. A NULL
character is added at the end of the string automatically when the user presses Enter key.
Syntax:
gets(variable);
The parameter variable is the variable that is used to store the string value.
puts()
The word 'put' stands for put string. The function is used to display a string value on the
screen. It can display both string variables as well as a string constant. The string constant is
enclosed in double quotation marks.
Syntax:
puts(variable);
The parameter variable is the variable whose value is to be displayed on the screen.
Example
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
void main()
{
clrscr();
char string[]= "This is an example output string";
puts(string);
getch();
}

pow()
The pow() function is used to find the result of one integer raised to the power ofthe second
integer (n).
Syntax:
pow(x, y);
x It indicates the first integer whose power is to be calculated.
y It indicates the second integer to be used as an exponent of the number.

Example
Write a program that inputs two integer numbers and displays the result of first number raise
to the power of second number using built-in function.
#include <iostream.h>
#include <conio.h>
#include <math.h>
void main()
{
clrscr();
int a, b;
cout<<"Enter first integer :";
cin>>a;
cout«"Enter second integer: ";
cin>>b;
cout<<"The result of pow(a,b) "<<pow(a,b);
getch();
}
sqrt()
The sqrt() function is used to calculate the square root of a floating-point number.
Syntax:
sqrt(x);
It indicates the floating-point number whose square root is to be calculated.

Lab Assignment:

1. Write a program that inputs a floating point number and displays its square root using
built-in function.
2. Write a program to calculate 2^5 using for loop and also using function.
3. Write a program to input String (your name and city) using the gets and display result
using puts function.
Lab Solution:
Q no 1: Write a program that inputs a floating point number and displays its square
root using built-in function.
Code:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float n;
cout << "Enter a floating point number\n";
cin >> n;
cout << "squar root of enterd floating point number is "<<sqrt(n)<<endl;
return 0;
}

Output:

Q no 2: Write a program to calculate 2^5 using for loop and also using function.
Code:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int base = 2 , exponent = 5;
int loop=1;
cout << "2^5 using for loop\n";
for (int i = 1; i <=exponent; i++)
{
loop*=base;
}
cout << loop<<endl;
cout << "2^5 using built in function is\n";
cout << pow(base,exponent)<<endl;
return 0;
}
Output:

Q no 3: Write a program to input String (your name and city) using the gets and
display result using puts function.
Code:
#include <stdio.h>
int main()
{
char name[30];
char city[30];
printf("Enter your name\n");
gets(name,30,stdin);
printf("Enter name of your city\n");
gets(city,30,stdin);
puts(name);
puts(city);
}

Output:

You might also like