Sei sulla pagina 1di 77

Mudassir Ahmad

16PWELE4963

Date: 18 June 2017.


Lab Instructor: Engineer Muhammad Farooq.
Name :- Mudassir Ahmad .

S.No :- 113 .

Registration No :- 16PWELE4963 .

Class :- 2nd Semester .

Section :- “D” .

Technology :- Electrical Communication .

Subject: Computer Programming .

Date :- 18 June 2017 .

Submitted To :- Engg. Muhammad Farooq .


Mid Term.
Mid term includes 5 lab’s and their respective lab task’s i.e,
Lecture No. 1
 A simple C++ progrramme.
 C++ Source Code.
Lecture No. 2
 Windows.h
 Sleep (time in millisecond)
 System (“ CLS”).
 Variables.
 Data Types.
 Int
 Float
 Double
 Char
 Bool
 String
 Operators.
 Increment and Decrement.
Lecture no. 3
 \r.
 Function and types.
 Local and global variables.
 Local and global function.
 Function overloading.
 Function templetes ( template <classT>).
 Math.h. { pow(x,y), sqrt(x), cos(x), sin(x), tan(x), Log(x), log10(x), exp(x) }.
Lecture no.4
 Relational expression and relational operators.
 Condition statements.
a . if statement.
b. if-else statement.
c. nested if statement.
d. nested if-else statement.
 Logical operators.
AND (&&).
OR (ll).
NOT (!).
 Recursion.
Lecture no.5
 The switch statement.
 Escape sequence.
\a, \b, \n, \r, \t, \\, \”.
 Loops.
a.For loop.
b.While loop.
c.Do-while loop.

Lecture No. 1
A simple C++ progrramme.
C++ Source Code.

1.A Simple C++ Programme.


Here is a simple C++ programme, in which you will learn how to work in C++ and the basic
environment required for it.

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
cout<<"Welcome to 2nd Semester";
getch ();
return o;
}
Now here:
#include = Preprocessor Directive
<iostream> = Header file. (the instruction in <> is known as Header File ).
Iostream is for input/output.
Getch (); is for getting charcter on console screen.

2.C++ Source Code.


A simple C++ source code consists of the folloiwng three elements:
i. Preprocessor Directives & Header Files.
ii. Main Function.
iii. C++ Statement.
A C++ statement ends with “ ; “.

Mudassir Ahmad : 16PWELE4963


Section “D”

Computer Programming Lab Task 01


#include<iostream>

#include<conio.h>

using namespace std;

int main ()

cout<<"Welcome to 2nd semester."

getch ();

return 0;

Lecture No. 2
Windows.h
 Sleep (time in millisecond)
 System (“ CLS”).
Variables.
Data Types.
 Int
 Float
 Double
 Char
 Bool
 String
Operators.
Increment and Decrement.

1.Windows.h
It is a header file which contains the definition of SLEEP and System “CLS”.
Sleep is a C++ statement that is used to generate a delay. To use sleep we include windows.h.
and the time of delay is writteni in paranthesis in milli-seconds. For 2-seconds delay we write
Sleep (2000);
And system(“CLS”) is used to clear the output console. Let we have to clear “Hello” after a
delay, then
Cout<<”Hello”;
Sleep(5000);
System (“CLS”);
2.Variables.
A value that may vary durin a program execution is known as “Variable”. Each variable has a
specific storage location in memory where its value is stored. Simply, a variable is a name used to
represent a piece of information.
3.Data Type.
Data type is the type of data stored in variable. Based on the data type of a variable, the operating
system allocates memory and decides what can be stored in the reserved memory.

Data Type Declaration name Size Range


Integer Int 4 byte -32768-32677
Float float 4 byte 1038-10-38
double double 8 byte 10-308-10308
Character char 1 byte 0-255
Boolean bool 1 byte 0-1
String string 4 byte

3.Operators.
To build relational expressions, two types of operators are used relational operators and
logical operators. Let's deal first with the relational operators and logical operators will be explain
later on.
There are six relational operators, four of equal precedence:
> greater than
>= greater than or equal to
< less than
<= less than or equal to
and two just below these in precedence:
== equal to
!= not equal to.

4.Increment & Decrement.


The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1
from its operand. Both the increment and decrement operators can either precede (prefix) or follow
(prefix) the operand.
++x (prefix) or x++ (prefix)
--x (prefix) or x-- (prefix)
If x=6 then
x++ means 6.
++x means 7.
Mudassir Ahmad : 16PWELE4963

Section “D”

Computer Programming Lab Task 02

#include<iostream>

#include<conio.h>

using namespace std;

int main ()

int a,b;

cout<<"enter value of a";

cin>>a;

cout<<"enter value of b";

cin>>b;

cout<<"sum of a and b"<<a+b<<endl;

getch ();

return 0;

Mudassir Ahmad : 16PWELE4963


Section “D”

Computer Programming Lab Task 03

#include<iostream>

#include<conio.h>

using namespace std;

int main ()

int a,b;

cout<<"enter value of a";

cin>>a;

cout<<"enter value of b";

cin>>b;

cout<<"addition of a and b"<<a+b<<endl;

cout<<"subtraction of a and b"<<a-b<<endl;

cout<<"multiplication of a and b"<<a*b<<endl;

cout<<"division of a and b"<<a/b<<endl;

getch ();

return 0;

Mudassir Ahmad : 16PWELE4963

Section “D”
Computer Programming Lab Task 04

#include<iostream>

#include<conio.h>

using namespace std;

int main()

int a,b;

cout<<"Enter value of a";

cin>>a;

cout<<"Enter value of b";

cin>>b;

a=a+b;

b=a-b;

a=a-b;

cout<<"After swap a: "<<a<<"b: "<<b;

getch();

Lecture no. 3
\r.
Function and types.
Local and global variables.
Local and global function.
Function overloading.
Function templetes ( template <classT>).
Math.h. { pow(x,y), sqrt(x), cos(x), sin(x), tan(x), Log(x), log10(x), exp(x) }.

1.\r .
r =CR (Carraige Return) // Used as a new line character.\ r Return the print head to the left
side. \r move the cursor to the begin of the line. \r is a carriage return character; it tells your
terminal emulator to move the cursor at the start of the line.The cursor is the position where the
next characters will be rendered.So, printing a \r allows to override the current line of the terminal
emulator.
cout << "Hello \r world!" << endl;
Now it will just appear “world!” on the console screen.
2.Functions.
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.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is such that each function performs a specific
task.
A function takes input and give us output and these are in the form of data. Now the input
and output data must be declared.
#include <iostream>
using namespace std;

// Function prototype (declaration)


int add(int, int);

int main()
{
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin >> num1 >> num2;

// Function call
sum = add(num1, num2);
cout << "Sum = " << sum;
return 0;
}

// Function definition
int add(int a, int b)
{
int add;
add = a + b;

// Return statement
return add;
}
Now there are three parts of functions they are described as under:
i.Function prototype (declaration)
If a user-defined function is defined after main() function, compiler will show error. It is because
compiler is unaware of user-defined function, types of argument passed to function and return
type.In C++, function prototype is a declaration of function without its body to give compiler
information about user-defined function. Function prototype in the above example is:
int add(int, int);
ou can see that, there is no body of function in prototype. Also, there are only return type of
arguments but no arguments. You can also declare function prototype as below but it's not necessary
to write arguments.
int add(int a, int b);
Note: It is not necessary to define prototype if user-defined function exists before main() function.
ii.Function Call
To execute the codes of function body, the user-defined function needs to be invoked(called).
In the above program, add(num1,num2); inside main() function calls the user-defined function.
The function returns an integer which is stored in variable add.
iii.Function Definition
The function itself is referred as function definition. Function definition in the above program is:
// Function definition
int add(int a,int b)
{
int add;
add = a + b;
return add;
}
When the function is called, control is transferred to the first statement of the function body.Then,
other statements in function body are executed sequentially.When all codes inside function
definition is executed, control of program moves to the calling program.
3.Local & Global Variables.
Scope of variables. A scope is a region of the program and broadly speaking there are three
places, where variables can be declared − Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters. Outside of all functions
which is called global variables. These variables can be accessed (ie known) by any function
comprising the program.
Local variables are declared inside a function, and can be used only inside that function. It is
possible to have local variables with the same name in different functions. The variables declared
inside the function are automatic or local variables.The local variables exist only inside the function
in which it is declared. When the function exits, the local variables are destroyed.

Global variables are declared outside any function, and they can be accessed (used) on any
function in the program. A global variable is a variable which is accessible in multiple scopes.  It is
important to note that global variables are only accessible after they have been declared.
#include <stdio.h>
void display();

int n = 5; // global variable

int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}

void display()
{
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}

Static VariableA static variable is declared by using keyword static.


For example;
static int i;
The value of a static variable persists until the end of the program.
Example #2: Static Variable
#include <stdio.h>
void display();

int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
c += 5;
}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.During the
second function call, variable c is not initialized to 0 again. It's because c is a static variable. So, 5 is
displayed on the screen.
4.Local and Global Functions.
Local functions are declared inside a function and they can be called or accesed only where
they are declared.
Global functions are the functions which are declared outside another function just after a
pre-processor directive and can be called for any other function.
Using namespace std;
Int sum(int x, int y)
Int main ()
{
………………………….
…………………………….
}

5.Function Overloading.
Two or more functions having same name but different argument(s) are known as
overloaded functions. In C++ programming, two functions can have same name if number and/or
type of arguments passed are different.These functions having different number or type (or both) of
parameters are known as overloaded functions. For example:
Int sum(int x , int y)
Int sum(int a , int b , int c)
float sum(int x , int y)
Here, all 4 functions are overloaded functions because argument(s) passed to these
functions are different.Notice that, the return type of all these 4 functions are not same. Overloaded
functions may or may not have different return type but it should have different argument(s).
7.Math.h.
It is a numerics library. Header <math.h> declares a set of functions to compute common
mathematical operations and transformations.
pow(x,y), Raise to power i.e xy.
sqrt(x), Compute square root.
sin(x), compute sine function.
cos(x), compute cosine function.
tan(x), compute tangent function.
Log(x), Compute natural logarithm.
log10(x), Compute common logarithm.
exp(x), Compute exponential function.
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 05
#include<iostream>
#include<conio.h>
using namespace std;
int main ()
{
int a,b,sum,diff,m,d;
cout<<"enter first number";
cin>>a;
cout<<"enter second number";
cin>>b;
int Sum(int a, int b);
int Diff(int a, int b);
int Mul(int a,int b);
int Div(int a,int b);
sum=Sum(a,b);
diff=Diff(a,b);
m=Mul(a,b);
d=Div(a,b);

cout<<sum<<endl;
cout<<diff<<endl;
cout<<m<<endl;
cout<<d<<endl;
getch ();
return 0;
}
int Sum(int a,int b)
{
int sum;
sum=a+b;
return sum;
}
int Diff(int a,int b)
{
int diff;
diff=a-b;
return diff;
}
int Mul(int a,int b)
{
int m;
m=a*b;
return m;
}
int Div(int a,int b)
{
int d;
d=a/b;
return d;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 06
#include <iostream>
using namespace std;
int main()
{
int kg,gm;
int grams (int);
cout<<"Enter Value in Kilograms ?";
cin>>kg;
gm = grams (kg);
cout<<"Answer in grams = "<<gm;
}
int grams (int val)
{
return val*1000;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 07
#include <math.h>
#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;

#define PI 3.14159265

int main ()
{
double a, result;
cout<<"enter a value";
cin>>a;
result = sin (a*PI/180);
result = cos (a*PI/180);
result = tan (a*PI/180);
cout<<"The sine of " << a << " degrees is " << result <<endl;
cout<<"The cos of " << a << " degrees is " << result <<endl;
cout<<"The tan of " << a << " degrees is " << result <<endl;
getch ();
return 0;
}
Lecture no.4
Relational expression and relational operators.
Condition statements.
a . if statement.
b. if-else statement.
c. nested if statement.
d. nested if-else statement.
Logical operators.
AND (&&).
OR (ll).
NOT (!).
Recursion.

1.Relational expression and relational operators.


Relational expression. A result that is either true or false. Such an expression is called a
relational expression. The result reflects how something "relates to" something else. Relational
expressions are usually intended to answer yes/no, or true/false, questions. Obviously, boolean
values and boolean variables play an important role in relational expressions.

Relational operators. To build relational expressions, two types of operators are used
relational operators and logical operators. Let's deal first with the relational operators and logical
operators will be explain later on.
There are six relational operators, four of equal precedence:
> greater than
>= greater than or equal to
< less than
<= less than or equal to
and two just below these in precedence:
== equal to
!= not equal to.
The following are examples of relational expressions built from relational operators: (the
result is also shown):
3 < 4 true
7.6 <= 9 true
4 == 7 false
8.3 != 2.1 true.

2.Conditional statements.
Conditional statements, also known as selection statements, are used to make decisions
based on a given condition. If the condition evaluates to True, a set of statements is executed,
otherwise another set of statements is executed.
a.The if Statement: The if statement selects and executes the statement(s) based on a given
condition. If the condition evaluates to True then a given set of statement(s) is executed. However, if
the condition evaluates to False, then the given set of statements is skipped and the program control
passes to the statement following the if statement. The syntax of the if statement is
If (condition)
{
Statement-1
Statement-2
Statement-3
}
b.The if-else Statement: The if - else statement causes one of the two possible statement(s) to
execute, depending upon the outcome of the conditions. The syntax of the if-else statements is
If (condition)
{
Statement-1
Statement-2
}
Else
{
Statement-3
Statement-4
}
Here, the if-else statement comprises two parts, namely, if and else. If the condition is True
the if part is executed. However, if the condition is False, the else part is executed.
c.Nested if Statement: A nested if statement contains one or more if statements. The syntax of the
nested if statement is
if (condition-1)
{
if (condition-2)
statement-1
statement-2
}
d.Nested if-else Statement: A nested if-else statement contains one or more if-else statements. The
syntax of the nested if-else statement is
if (condition-1)
statement-1
else if (condition-2)
statement-2
else if (condition-3)
statement-3
else
statement-4

3.Logical operators.
The logical operators apply logic functions to boolean arguments. There are three logical operators:
&& AND (true if both arguments are true, false otherwise).
|| OR (true if either argument is true, false otherwise).
! NOT (true if argument is false, false otherwise).
a.AND operator.
The "and" operator in C++ is represented by two ampersand signs next to each other: &&. It
takes the boolean value on the left of the operator and the boolean value on the right of the
operator, and returns true if both are true, and false in all other conditions. if condition A and
condition B are true, then the expression will be true, otherwise the expression will be false. This
means that true && true will evaluate to true, and true && false will evaluate to false --
both conditions must be true for the expression to be true. An example of this is as follows:
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
if(age >= 35 && age <= 80)
{
cout << "You're between 35 and 80 and can save money on your car insurance!" << endl;
}
else
{
cout << "Sorry, we don't have any deals for you today!" << endl;
}

return 0;
}
b.OR operator.
The "or" operator behaves much like "and", however only one of the two conditions has to
be true. It is represented by a double "pipe symbol", ||, and behaves much like the word "or" in the
English language - if one condition or the other is true. This means that true || true, true ||
false, and false || true will all return true, and false || false will return false. An
example of this is as follows:
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;

if(age < 0 || age > 160)


{
cout << "You're lying - you CANNOT be that age." << endl;
}
else
{
cout << "Thanks for inputting your age!" << endl;
}

return 0;
}

c.NOT operator.
The "not" operator is a little different to "and" and "or". It can only be prefixed to single
expressions and essentially just inverts the boolean value of an expression. If the value is true, "not"
will flick it to false - the "not" operator is expressed via an exclamation mark, and hence !true is
false, and !false is true. The functionality of the "not" operator can almost always be
accomplished via different means, for example !(age > 5) could be expressed as age < 5.
If (!(x==y))

4.Recursion.
Recursion is when a function calls itself.
// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int);

int main()
{
int n;
cout<<"Enter a number to find factorial: ";
cin >> n;
cout << "Factorial of " << n <<" = " << factorial(n);
return 0;
}

int factorial(int n)
{
if (n > 1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 08
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int year;
cout<<"enter year";
cin>>year;
if (year%4==0)
cout<<"year is leap";
else
cout<<"year is not leap";
getch ();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 09
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
double net,bp,med,rent,con;
cout<<"enter the basic pay";
cin>>basic pay;
rent=0.45*bp
if(bp>30000)
{
med=0.02*bp;
con=10000;
}
else(bp<30000)
{ med=0.05*bp;
con=8000;
}
net=bp+med+con+rent;
cout<<"the net pay is"<<net;
getch ();
return 0;
}
Lecture no.5
The switch statement.
Escape sequence.
\a, \b, \n, \r, \t, \\, \”.
Loops.
a.For loop.
b.While loop.
c.Do-while loop.
1.The switch statement.
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case. Transfers control
to one of the several statements, depending on the value of a condition.
Syntax.
switch (integral_expression )
{
case constant1:
statements1;
break;
case constant2:
statements2;
break;
default:
statements;
}
If condition evaluates to the value that is equal to the value of one of constant_expressions,
then control is transferred to the statement that is labeled with that constant_expression.
If condition  evaluates to the value that doesn't match any of the case: labels, and
the default: label is present, control is transferred to the statement labeled with the default
label.
2.Escape sequence.
An escape sequence is a sequence of characters that does not represent itself when used
inside a character or string literal, but is translated into another character or a sequence of
characters that may be difficult or impossible to represent directly. An escape sequence is two or
more characters that often begin with an escape character that tells the computer or software
program to perform a function or command.
\a = Alert or beep.
\b = Back space.
\n = New line.
\r = Carriage return.
\t = Horizantal tab.
\\ = Back slash.
\” = Double quote.
3.Loops.

In any programming language, loops are used to execute a set of statements repeatedly until
a particular condition is satisfied.
A sequence of statement is executed until a specified condition is true. This sequence of
statement to be executed is kept inside the curly braces { } known as loop body. After every
execution of loop body, condition is checked, and if it is found to be true the loop body is executed
again. When condition check comes out to be false, the loop body will not be executed.
There are three type of loops in C++ programming:
A.for loop. B.while loop. C.do-while loop.
A.for loop.
for loop is used to execute a set of statement repeatedly until a particular condition is
satisfied. The initialization statement is executed only once at the beginning. Then, the test
expression is evaluated. If the test expression is false, for loop is terminated. But if the test
expression is true, codes inside body of for loop is executed and update expression is updated. Again,
the test expression is evaluated and this process repeats until the test expression is false.
General format is,
For (initialization; condition; increment/decrement)
{
Statement-block
}.
Example;
int i;
for(i=0; i < 2; i++)
{
cout << “iteration “ << i << endl;
}.
B.while loop.
The while loop is a pre-test loop just like the for loop, the program evaluates the test
expression before entering the statement(s) within the body of the loop.
The while loop evaluates the test expression. I f the test expression is true, codes inside the
body of while loop is evaluated. Then, the test expression is evaluated again. This process goes on
until the test expression is false. When the test expression is false, while loop is terminated.
General format is,
While (test expression)
{
Statement;
Increment/decrement
}.
Example;
int i;
i = 0;
while(i < 2)
{
cout << “ iteration “ << i << endl;
i = i + 1;
}.
C.do-while loop.
In some situations it is necessary to execute body of the loop before testing the condition.
Such situations can be handled with the help of do-while loop. do statement evaluates the body of
the loop first and at the end, the condition is checked using while statement.
The codes inside the body of loop is executed at least once. Then, only the test expression is checked.
If the test expression is true, the body of loop is executed. This process continues until the test
expression becomes false. When the test expression is false, do...while loop is terminated.
General format is,
Do
{
statements
}
while (test-expression);
Example;
int i;
i = 0;
do
{
cout << “iteration “ << i << endl;
i = i + 1;
}
while( i<2 );
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 10
#include <iostream>
#include <conio.h>
using namespace std;
int main();
{
char a;
cin>>a;
switch (a)
{
case 'a':
cout<<"char is a vowel";
break;
case 'e':
cout<<"char is a vowel";
break;
case 'i':
cout<<"char is a vowel";
break;
case 'o':
cout<<"char is a vowel";
case 'u':
cout<<"char is a vowel";
break;
default
cout<<"char is a consonant";
}
getch ();
return 0;
}.
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 11

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

int main()
{
int a,b,c;
cin>>a>>b;
cout<<pow(a,b)<<endl;
c=a;
for(;b>=2;b--)
{
a=a*c;
}
cout<<a;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 12

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

int main()
{
int a,b,c,d=50;
cout<<"Enter a number : ";
cin>>a;
b=a;
while(b>=1)
{
cout<<setw(d);
c=b%2;
b=b/2;
d=d-2;
cout<<c;
cout<<"\r";
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 13
#include <iostream>
#include <conio.h>
using namespace std;
void binary1(int num)
{
if(num<=1)
{
cout<<num<<" ";
return;
}
int rem = num %2;
binary1(num/2);
cout<<rem<<" ";
}
//OR
void binary2(int n)
{
if (n / 2 != 0) {
binary2(n / 2);
}
cout<<n % 2;
}
int main()
{
int number;
cin>>number;
binary1(number);
cout<<endl;
binary2(number);
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 14

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
float sum = 1;
int a=2;
while(a<=45)
{
sum=sum+1.0/a;
a++;
}
cout<<sum;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 15

#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
for(int i=1;i<=3;i++)
{
for(int j=1,k=1;j<=5;j++)
{
cout<<k<<"\t";
k=k+i;
}
cout<<endl;
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 16

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

int main()
{
for(int i=1;i<=6;i++)
{
for(int j=1;j<=i;j++)
{
cout<<j<<"\t";
}
cout<<endl;
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 17

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

int main()
{
int d=10;
cout<<setw(d);
for(int i=1;i<=8;i=i+2)
{
for(int j=1;j<=i;j++)
{
cout<<"*";
}
cout<<endl;
d--;
cout<<setw(d);
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 18

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

int main()
{
for(int i=2;i<=100;i++)
{
int j=2;
for(;j<i;j++)
{
if(i%j==0)
break;
}
if(i==j)
cout<<i<<"\t";
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 19

#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
double factorial(double x)
{
if(x>1)
return x*factorial(x-1);
else
return 1;
}
int main()
{
double x,Result=1;
cin>>x;
cout<<"Actual value : "<<exp(x)<<endl;
for(int i=1;i<=50;i++)
{
Result=Result+pow(x,i)/factorial(i);
}
cout<<"Calculated Value : "<<Result;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 20

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

int main()
{
for(int i=1;i<=9;i++)
{
for(int j=i;j>=1;j--)
{
cout<<j<<"___";
}
cout<<endl;
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 21

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

int main()
{
int a,b,max;
cout<<"Enter Two numbers : ";
cin>>a>>b;
max=(a>b)?a:b;
while(1)
{
if((max%a==0)&&(max%b==0))
break;
max++;
}
cout<<"LCM of the two numbers is : "<<max;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 22

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x,y,temp,i;
cout<<"Enter the two numbers : ";
cin>>x>>y;
if(y>x)
{
temp=x;
x=y;
y=temp;
}
for(i=y;i>=1;i--)
{
if((x%i==0)&&(y%i==0))
break;
}
cout<<i;
getch();
return 0;
}
Final Term.
Final term includes 6 lab’s and their respective lab task’s i.e,
Lecture No.1
 Delays.
 C ++ Class Strings.
 Initialization.
 Assigning.
 Concateration
 Input & Output Strings.
 cin>>a
 getline(cin, a).
 getline (cin, a, ‘ *’ ).
 String Name find(-----------).
 Modifying Strings.
 Erase.
 Replace.
 Insert.
 Size( ).
 Comparing strings.
 Newton Raphson Method.
Lecture no. 2
 Trapezoid Rule.
 Random Number Generation.
Lecture No. 3
 Arrays.
 One Dimensional Array.
 Two Dimensional Array.
 Character Array.
 Passing Function to Array.
Lecture No.4
 Reference Parameter.
 Argument Passed By Value.
 Argument Passed By Reference.
 Sorting Array.
 Bubble Sorting.
 Selection Sorting.
Lecture No.5
 Searching In Array.
 Linear search.
 Binary search.
Lecture No.6
 Structures.
 Pointer’s.
Lecture no. 1
Delays.
C++ Class Strings.
 Initialization.
 Assigning.
 Concateration
 Swap ( , )
Input & Output Strings.
 cin>>a
 getline(cin, a).
 getline (cin, a, ‘ *’ ).
String Name find(-----------).
Modifying Strings.
 Erase.
 Replace.
 Insert.
Size( ).
Comparing strings.
Newton Raphson Method.

1.Delays.
Delays also be generated without builtin functions such as.
{
For (int a=1; a<=1000; a++)
For (int a=1; a<=1000; a++)
For (int a=1; a<=1000; a++);
Cout<<”hi”;
Return 0;
}
So it will show hi after some time.

2.C++ Class Strings.


Strings are objects that represent sequences of characters.
>> initialization.
For initialization
String a; OR
String a=”hi”; ALSO
String a(“hi”);
>> assigning.
String a;
c=a;
here value of a is assigned to c.
>> concateration.
String a,b;
a=”hi”; b=”mom”;
String c;
c=a+b;
here cout<<c will display himom but if we write :
c=a+” “+b;
then it will display hi mom
>> swap
For swaping :
Swap(a, b);
The the values will be interchanged…… i.e hi to mom amd mom to hi like “” mom hi “”,

3.Input/Output strings.
Input can be taken in the followig ways from the user’s. they are explained as under:
>>cin>>a.
If there is not any space between the word then we use only cin>>a. let if I want to write only
Mudassir then I will use it bust if I write “Mudassir Ahmad” then it will only show Mudassir on the
console screen and Ahmad will be neglected.
>>getline(cin , a).
Now if we have more then one word then we use it. i.e if we have spaces in between it we
use grline(cin , a).
>>getline(cin , a , “ * “ ).
It is used when we have a paragragh, because it is not written with the getline( cin , a )…. For
a paragragh we use getline(cin , a , “ * “ ). Now the sign used inside “ “ will end up the operation
when written at the end.

4.String Name Find (---------).


Let if we have to find a word then we use the string name and the word thet we want to find.
stringname find( ).
String a= “hello ellie, I love ur song ANYTHING COULD HAPPEN”;
Int b;
b=afind(“love”);
now it will show the positionn of love i.e 15 starting with index value 0.

5.Modifying String.
Following are some modifying strings i.e if we want to erase, replace or insert something in
the string.
>>Erase.
string a=”Saba Qamar is my favourite actress”;
now write the name of the string i.e
a.erase ( , );
Here two arguments are in the brackets the first one is for position of the word and the other
is the size of word. Let I want to erase is then
a.erase(11,2);
cout<<a;
>>Replace.
If I want to replace favourite with best-loved then we use the position of that word, size of
word and in qoutes that word “best-loved”.
a.replace(11,2,”beat-loved”);
>>insert.
If we want to insert some word then
a.insert(18,”most”);
now here 18 is the position wheree the word should be inserted and in qoutes the word.
6.Size( ).
To find the size of a string, we write string name and size with brackets.
a.size( )
7.Comparing String.
Equal to (==) operator is used for comparing.
Int main()
{
String password=”emma”;
String a;
cout<<”enter pass word”;
cin>>a;
if (a==password)
cout<<”matched”;
else
cout<<”incorrect”;
getch ();
return 0;
}

8.Newton Raphson Method.


Newton raohson method is used to find the roots of an equation using numerical analysis.
Xn+1= Xn –
The ALOGRATHIM of this method is
 Enter a guess value.
 Enter accuracy required.
 Repeat
 Xn+1= Xn –
 Until | Xn+1 - Xn | < e.
 Print Xn+1.
Lecture no. 2
Trapezoid Rule.
Random Number Generation.

1.Trapeziod Rule.
It is used to find the definite integral pf a function. Definite integral means that its limits are
given. Trapezoid is a geometric shape whose two sides are parallel and two are not. And its area is
given by (b1+b2)
Area under the curve between a and b is

The alogrithim for the trapiozed rule is:


 Enter initial and final limits i.e a and b.
 Enter the number of intervals.
 ∆x=
 Using loop find
= ∆x/2 [ f(x0)+2f(x1)+2f(x2)………………+2f(xn-1)+f(x0) ]
 Display result.

2.Random Number Generation.


We use built-in library for the generation of random numbers. These libraries are
#inclide<cstdlib>
#include<ctime>
In order to use it we need to include the <cstdlib> header. To generate a random number we
use the rand() function. We can seed the generator with the srand() function. This will start the
generator from a point in the sequence that is dependent on the value we pass as an argument. If we
seed the generator once with a variable value, for instance the system time, before our first call of
rand() we can generate numbers that are random enough for simple use (though not for serious
statistical purposes).
#include<iostream>
#include<conio.h>
#include<cstdlib>
#include<ctime>
Int main ()
{
Srand(time(0));
Int x=rand()%6;
cout<<x;
getch ();
return 0;
}
Here division by 6 gives 0------5 & division by 6+1 gives 1----6.
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 26
#include<iostream>
#include<conio.h>
using namespace std;
double f(double x)
{
return (1/(x*x));
}
int main()
{
double a,b,n,result,del_x;
cout<<"enter initail and final limit's:";
cin>>a>>b;
cout<<"enter interval:";
cin>>n;
del_x=b-a/n;
result=f(a);
for (x=a+del_x; x<b; x=x+del_x)
{
result=result+2*f(x);
}
result=result+f(b);
result=result*del_x/2;
cout<<result;
getch ();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 27
#include<iostream>
#include<conio.h>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
int x=rand( )%54+4960;
cout<<x;
getch ();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 28
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
string myfilename, mystring;

cout << "Enter the name of the file to open\n";


cin >> myfilename;

ifstream inFile;
inFile.open(myfilename.c_str());

if (!inFile) {
cout << "Error opening file " << myfilename << endl;
return -1;
}
while(!inFile.eof()) {
getline(inFile, mystring);
cout << mystring << endl;
}
inFile.close();
}
/*
//writing in a file//
int main ()
{
ofstream outFile(“myoutfile.txt”);

if (!outFile) {
cout << “Error opening file” << endl;
return -1;
}
outFile << “This is my output file.” << endl;
outFile.close();
}
/*
//Appending in a file//
int main ()
{
ofstream outFile(“myoutfile.txt”, ios::app);

if (!outFile) {
cout << “Error opening file” << endl;
return -1;
}
outFile << “This is my output file.” << endl;
outFile.close();
Lecture No. 3
Arrays.
 One Dimensional Array.
 Two Dimensional Array.
Character Array.
Passing Function to Array.

1.Arrays.
An array is a collection of data that holds fixed number of values of same 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.
Following are the two types of array:
 One Dimensional Array.
 Two Dimensional Array.
They are explained as under:
>>One dimensional Array (1-D).
A one dimensional array is known as a “list”. A list of items can be given one variable name
using only one subscript and such a variable is called single sub-scripted variable or one dimensional
array.
Declaration of 1-D array.
 Write type of data.
 Write name of array.
 Show size of array in [ ].
Type array-name[size];
Int marks [9];
Accessing to 1-D array.
 Mention the name of array.
 Write the index Value.
Index vaiue starts from zero and ends at less the the size of array ( 0-------n-1 ).
Marks[6];
Storing data in 1-D array.
Data can be stored in three ways.
1.Assignment operator:
Int marks[3];
Marks[0]=12;
Marks[1]=42;
Marks[2]=21;
2.Using cin:
Int marks[3];
Cin>>Marks[0];
Cin>>Marks[1];
Cin>>Marks[2];
And loop can also be used;
Int marks[3];
For(int i=0; i<=3; i++);
Cin>>marks[i];
3.Explicit initialization.
In this method values are assign in single line.
Int marks[3]={67, 98.76};
= sign and also the size of array can be ignored In explicit initialization.
Output from 1-D array.
Out is take on console screen with the help of cout<<.
Cout<<marks[2];
And also loop is applied to get output.
For(int i=0; i<=3; i++);
Cout<<marks[i];
>>Two Dimensional Array (2-D).
It is also known as a table or matrice. As data is stored in rows and coloumn.
Declaration of 2-D array.
 Type of array.
 Name of array.
 Mention number of rows and coloumn in braces [ ] [ ].
Type array-name[rows][coloumn];
Int marks[2][3];
Number of elements is found by multiplying rows and coloumn.
Access to 2-D array.
Now here it will be having two subscripts i.e one for accessing member of row and other
accessing member of coloumn.
Array-name[row][coloumn];
Marks[0][0];
Storing data in 2-D array.
Data is stored in the same way as in 1-D but with naming rows and coloumns.
1.Assignment operator:
int marks[2][2];
marks[0][0]=13;
marks[0][1]=54;
marks[1][0]=21;
marks[1][1]=43;
2.Using cin:
Cin>>marks[0][0];
Cin>>marks[0][1];
Cin>>marks[1][0];
Cin>>marks[1][1];
Or by nested loop;

For (int r=0; r<=2; r++)


{
For(int c=0; c<=2; c++)
Cin>>marks[r][c];
}
3.Explicit initialization.
Int marks[2][2]={ {23,43}, {43,12} };
Output from 2-D array.
Out is simply taken by using cout,
Cout<<[0][1];
OR
Int marks[2][2];
For (int r=0; r<=2; r++)
{
For(int c=0; c<=2; c++)
{
cout<<marks[r][c]<<”t”;
Cout<<endl;
}
3.Character Array.
char abc[3]={‘h’, ‘I’, ‘\0’};
here the last element is known as null character as it is used to tell the compiler tahat the
array end’s at that point. Further more a character array doesn’t need to call by cout for output on
console screen and also loop is not needed for output. Let consider if user enter more character then
it also increases the size by itself.
char abc[3];
cin>>abc;
cout<<abc;
4.Passing Array to function.
Arrays can be passed to a functionhttps://www.programiz.com/cpp-programming/function
as an argument.
>>Function declaration.
type function-name(arguments);
for array
return-type(arguments);
(type-array [ ], float[ ]);
(int [ ], float[ ]);
>>Function definition.
Int name ( int a[ ], float[ ])
Here in function definition ‘a’ And ‘b’ are compulsory and the funcyion is with no semicolon ;
{
Function body;
};
>>Calling a function.
Int abc [5];
Name (abc);
Int abc[5];
Float abc[5];
Name(abc, xyz);
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 29
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int integers[25];
int positive=0,negative=0,even=0,odd=0;
for (int i=0; i<=4; i++)
{
cin>>integers[i];
if (integers[i]>0)
positive+=1;
if (integers[i]<0)
negative+=1;
if (integers[i]%2==0)
even+=1;
if ((integers[i]%2==1)||(integers[i]%2==-1))
odd+=1;
}
cout<<"Positive numbers are :"<<positive<<endl;
cout<<"Negative numbers are :"<<negative<<endl;
cout<<"Even numbers are :"<<even<<endl;
cout<<"Odd numbers are :"<<odd;
getch ();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 30
#include <iostream>
#include<conio.h>
using namespace std;
void mean(int a[],int a_size)
{
a_size=6;
int sum=0;
for(int i=0;i<=5;i++)
{
sum=sum+a[i];
}
float mean=(float)sum/a_size;
cout<<"\nThe mean of the array elements is : "<< mean;
}
void display(int a[],int a_size)
{
for(int i=0;i<=5;i++)
{
cout<<"array ["<<i<<"]\t"<<a[i]<<endl;
}
}
int main()
{
int arry[6]={2,4,6,8,10,12};
int size=6;
display(arry,size );
mean(arry,size);

getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 31

#include <iostream>
#include<conio.h>
#include <windows.h>
using namespace std;
int main()
{
int arry[10];
cout<< "Enter the array elements\n";
for(int i=0;i<=9;i++)
{
cin>>arry[i];
}
system("cls");
cout<<"\t"<<"Element\tValue\tHistogram\n";
for(int i=0;i<=9;i++)
{
cout<<"\t "<<i<<"\t "<<arry[i]<<"\t";
for(int s=1;s<=arry[i];s++)
{
cout<<"*";
}
cout<<endl;
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 32

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int arry[5][5];
for(int r=0;r<=4;r++)
{
for(int c=0;c<=4;c++)
{
cin>>arry[r][c];
}
}
int max= arry[0][0];
for(int r=0;r<=4;r++)
{
for(int c=0;c<=4;c++)
{
if(max<arry[r][c])
max=arry[r][c];
}
}
cout<<max;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 33
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int matrix[4][4];
cout<<"Enter the entries of a 4 by 4 Matrix\n";
for(int r=0;r<=3;r++)
{
for(int c=0;c<=3;c++)
{
cin>>matrix[r][c];
}
}
cout<< "The obtained matrix is : \n";
for(int r=0;r<=3;r++)
{
for(int c=0;c<=3;c++)
{
cout<<"\t"<<matrix[r][c]<<"\t";
}
cout<<endl;
}
cout<<"\nThe required Transpose of the matrix is :\n";
for(int r=0;r<=3;r++)
{
for(int c=0;c<=3;c++)
{
cout<<"\t"<<matrix[c][r]<<"\t";
}
cout<<endl;
}
getch();
return 0;
}
Lecture No.4
Reference Parameter.
 Argument Passed By Value.
 Argument Passed By Reference.
Sorting Array.
 Bubble Sorting.
 Selection Sorting.

1.Reference Parameters.
The argument may be passed by value or by reference. They are explained as follows:
>>Argument Passed By Values.
By default, arguments in C++ are passed by value. When an argument is passed by value, the
argument’s value is copied into the function’s parameter. Arguments passed by value can be
variables (e.g. x), literals (e.g. 6), expressions (e.g. x+1), structs & classes, and enumerators.
Arguments are never changed by the function being called, which prevents side effects.
int main()
{
viod exch(int , int);
int a=10;
int b=20;
exch (a,b);
cout<<a<<endl;
cout<<b<<endl;
}
viod exch(int , int)
{
int temp p=x;
x=y;
y=temp;
}
>>Argument Passed By Reference.
To pass a variable by reference, we simply declare the function parameters as references
rather than as normal variables. We access memory location in it & is used for that.
int main()
{
viod exch(int& , int&);
int a=10;
int b=20;
exch (a,b);
cout<<a<<endl;
cout<<b<<endl;
}
viod exch(int& , int&)
{
int temp p=x;
x=y;
y=temp;
}
2.Sorting Arrary.
Sorting is the process of putting data in order either numerically or alphabetically. It is often
necessary to arrange the elements in an array in numerical order from highest to lowest values
(descending order) or vice versa (ascending order) .  If the array contains string values, alphabetical
order may be needed. The process of sorting an array requires the exchanging of values.  While this
seems to be a simple process, a computer must be careful that no values are lost during this
exchange.
Two ways to sort array.
>>Bubble Sorting.
In the bubble sorting, as elements are sorted they gradually "bubble" (or rise) to their proper
location in the array. The bubble sort repeatedly compares adjacent element of an array.  The first
and second elements are compared and swapped if out of order.  Then the second and third
elements are compared and swapped if out of order.  This sorting process continues until the last two
elements of the array are compared and swapped if out of order.
The bubble sort is an easy algorithm to program, but it is slower than many other sorts.  With
a bubble sort, it is always necessary to make one final "pass" through the array to check to see that
no swaps are made to ensure that the process is finished.  In actuality, the process is finished before
this last pass is made. Let we have 5 elements in an array then there will be 4 iterations i.e 1-4 or 0-3.
We require a nested loop for it. The outer loop controls the number of iteration and the second loop
controls number of comparision.
>>Selection Sorting.
The selection sort is a combination of searching and sorting. During each pass, the unsorted
element with the smallest or largest value is moved to its proper position in array. The number of
times the sort passes through the array is one less than the number of items in the array.  In the
selection sort, the inner loop finds the next smallest (or largest) value and the outer loop places that
value into its proper location.
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 34

#include <iostream>
#include <conio.h>
using namespace std
void bubblesort(int a[],int n)
{
for(int i=0;i<=n-2;i++)
{
for(int j=0;j<=n-2;j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
void Median (int a[],int n)
{
cout<<"The median is element "<<n/2<<" of the sorted "<<n<<" elements array. For this run the
median is "<<a[n/2];
}
int main()
{
int size = 15, A[size] = {13,7,1,15,10,8,2,9,3,12,4,11,5,14,6};
bubblesort(A,size);
cout<<"Sorted Array is : "<<endl;
for(int i=0;i<=size-1;i++)
cout<<A[i]<<"\t";
cout<<endl<<endl;
Median(A,size);
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 35
#include <iostream>
#include <conio.h>
using namespace std;
int size=10;
void frequency (int a[],int n)
{
int f=0;
for(int i=0; i<size; i++)
{
if(n==a[i])
f++;
}
cout<<"The element "<<n<<" appears "<<f<<" times in the array";
}
int main()
{
int a[size] = {2,2,2,1,1,3,5,5,5,5};
int n;
cout<<"Enter The element : ";
cin>>n;
frequency(a,n);
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 36
#include <iostream>
#include <conio.h>
using namespace std;
void Display(int a[][4])
{
for(int r=0;r<=3;r++)
{
for(int c=0;c<=3;c++)
cout<<a[r][c]<<"\t";
cout<<endl<<endl;
}
}
int main()
{
int a[4][4] = {{12, 13, 19, 20},
{13, 25, 49, 56},
{14, 23, 67, 59},
{15, 45, 48, 41}};
cout<<"Before sorting : "<<endl;
Display(a);
for(int i=0;i<=14;i++)
{
for(int r=0;r<=3;r++)
{
for(int c=0;c<=3;c++)
{
if(a[r][c] > a[r][c+1])
{
int temp = a[r][c];
a[r][c] = a[r][c+1];
a[r][c+1] = temp;
}

}
}
}
cout<<"After sorting : "<<endl;
Display(a);
getch();
return 0;
}
Lecture No.5
Searching In Array.
 Linear search.
 Binary search.

1.Searching In An Array.
A common programming task is to search an array for a given target value. If the target value
is found, we want to know the index of the element holding that target value. We will write a
function to perform this task. The simplest way is to use the sequential search algorithm: the
function inspects each element in the array from the first to the last element (or vice versa) to see if
it matches the target value. Once a match is found, the function returns the index of the element
whose value matches the target value. If no match is found after inspecting all the elements of the
array, then the function returns -1. Since a -1 cannot be the index of an array element, this value
indicates that a match is not found.
>>Linear Search.
It is used for a sorted array. It is a simple method. Linear search requires the following steps.
 Enter a search key.
 Compare it with first element of array.
 If it matches with key, alograthim ends.
 If not matched, compare it with 2nd element and so on.
Linear search is slow then binary and is also in-sufficient for large array.
>>Binary Search.
It is used for sorted array and is used for a larger array. It has less number of iteration than
the linear search. In binary search we must first sort the array. When searching an array, the binary
search process utilizes this same concept of splitting intervals in half as a means of finding the "key"
value as quickly as possible.
 Enter a search key.
 Compare search key with the middle element of array.
 If matched, return index of middle element.
 If search key is not matched then go for the second half.
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 37
#include <iostream>
#include <conio.h>
using namespace std;
int linearsearch(int x[],int size,int key)
{
static int i=0;
if(i==size)
return -1;
else if(key == x[i])
return i;
else
{
i++;
linearsearch(x,size,key);
}
}
int main()
{
int size=5,Position,key;
int A[size]={5,3,9,1,23};
cout<<"Enter Search key : ";
cin>>key;
Position=linearsearch(A,size,key);
if(Position == -1)
cout<<"Value not found";
else
cout<<"value founded at index "<<Position;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 38

#include <iostream>
#include <conio.h>
using namespace std;
int BinarySearch (int a[],int size,int key)
{
int low = 0;
int high = size-1;
int middle = (low + high + 1)/2;
do
{
if(key == a[middle])
return middle;
else if(key < a[middle])
low = middle + 1;
else
high = middle - 1;
middle = (low + high + 1)/2;
}while(low <= high);
return -1;
}
int main()
{
int size = 6, position, key;
int data[size] = {10,8,6,4,2,0};
cout<<"Enter Search key : ";
cin>>key;
position = BinarySearch(data,size,key);
if(position == -1)
cout<<"Not Found";
else
cout<<"Value founded at index "<<position;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 39
#include <iostream>
#include <conio.h>
using namespace std;
int BinarySearch (int a[],int key,int low,int high)
{
int middle = (low + high + 1)/2;
if(low > high)
return -1;
if(key == a[middle])
return middle;
else if(key > a[middle])
low = middle + 1;
else
high = middle - 1;
BinarySearch(a,key,low,high);
}
int main()
{
int size = 10, position, key;
int data[size] = {0,1,2,3,4,5,13,14,67,90};
cout<<"Enter Search key : ";
cin>>key;
position = BinarySearch(data,key,0,(size - 1));
if(position == -1)
cout<<"Not Found";
else
cout<<"Value founded at index "<<position;
getch();
return 0;
}
Lecture No.6
Structures.
Pointer’s.

1.Structures.
Structure is a collection of variables of different data types under a single name. It is similar
to a class in that, both holds a collecion of data of different data types. A data structure is a group of
data elements grouped together under one name. These data elements, known as members, can
have different types and different lengths. Data structures can be declared in C++ using the following
syntax:

struct type_name ------------ struct student


{ ------------ {
member_type1 member_name1; ------------ string name;
member_type2 member_name2; ------------ int age;
member_type3 member_name3; ------------ };
.
.
} object_names;

Where type_name is a name for the structure type, object_name can be a set of valid identifiers
for objects that have the type of this structure. Within braces {}, there is a list with the data
members, each one is specified with a type and a valid identifier as its name.
>>How To Declare Structure Variables.
Mention type and name of variable.student s1,s2.
>>How To Access Element’s Of Structure.
Dot ( . ) operator is used for accessing element of a structure.
S1.name;
S1.age;
S2.name;
S2.age;
>>Putting Data In Structure.
Data can be put in a structure by ‘initialization’ or ‘assignment operator’ or ‘cin’ method.
S1.name=”ELLIE”;
S1.age=”35”;
OR
S1={“ELLIE” , “35”};
S2={“EMMA” , “26”};
OR
Cin>>s1.name;
Cin>>s2.name;
>>Displaying Structure Data.
Data can be displayed by using cout<<;
Cout<<s1.name<<endl;
Cout<<s1.age<<endl;
2.Pointer’s.
Pointers are used in C++ program to access the memory and manipulate the address.
+Pointers Variables.
You can assign and de-assign any space in the memory as you wish. This is done using Pointer
variables.Pointers variables are variables that points to a specific address in the memory pointed by
another variable.
+How To Declare A Pointer.
int *p;
OR,
int* p;
The statement above defines a pointer variable p. It holds the memory address
The asterisk is a dereference operator which means pointer to. Here, pointer p is a pointer to int,
i.e., it is pointing to an integer value in the memory address.
Let;
Int a=10;
Int *p;
P=&a;
Then also
Cout<<&a;
Cout<<p;
Cout<<a;
Cout<<*p;
Cout<<&a;
Futher more
Double a=’a’;
Double *p=&a;
Cout<<p<<endl;
P=p+1;
Cout<<p<<endl;
It will shows
0 x 28ff00
0 x 28ff8 i.e incremented by 8 ( as doubles has 8bytes)

Mudassir Ahmad : 16PWELE4963


Section “D”
Computer Programming Lab Task 40

#include <iostream>
#include <conio.h>
using namespace std;
struct employee
{
string name;
int age;
int salary;
};
int main()
{
employee e1;
cout<<"Enter Name : ";
getline(cin,e1.name);
cout<<"Enter age : ";
cin>>e1.age;
cout<<"Enter Salary : ";
cin>>e1.salary;
cout<<"......................................................"<<endl;
cout<<"Name : "<<e1.name<<"\t"<<"Age : "<<e1.age<<"\t"<<"Salary : "<<e1.salary<<endl;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 41

#include <iostream>
#include <conio.h>
using namespace std;
struct complex
{
float real;
float imaginary;
};
void add (complex c1,complex c2)
{
cout<<"Addition is : ";
cout<<(c1.real+c2.real)<<" + "<<(c1.imaginary+c2.imaginary)<<"j"<<endl;
}
void sub (complex c1,complex c2)
{
cout<<"subtraction is : ";
cout<<(c1.real-c2.real)<<" + "<<(c1.imaginary-c2.imaginary)<<"j"<<endl;
}
void Mul (complex c1,complex c2)
{
float r = c1.real*c2.real - c1.imaginary*c2.imaginary;
float i = c1.real*c2.imaginary + c2.real*c1.imaginary;
cout<<"Multiplication is : ";
cout<<r<<" + "<<i<<"j"<<endl;
}
void Div (complex c1,complex c2)
{
float r = (c1.real*c2.real + c1.imaginary*c2.imaginary)/(c2.real*c2.real +
c2.imaginary*c2.imaginary);
float i = (-c1.real*c2.imaginary + c2.real*c1.imaginary)/(c2.real*c2.real +
c2.imaginary*c2.imaginary);
cout<<"Division is : ";
cout<<r<<" + "<<i<<"j"<<endl;
}
int main()
{
complex c1,c2;
cout<<"Enter 1st complex No with real and imaginary parts separated by commas : ";
cin >>c1.real>>c1.imaginary;
cout<<"Enter 2nd complex No with real and imaginary parts separated by commas : ";
cin >>c2.real>>c2.imaginary;
cout<<endl;
add(c1,c2);
sub(c1,c2);
Mul(c1,c2);
Div(c1,c2);
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 42

#include <iostream>
#include <conio.h>
using namespace std;
struct student
{
int rollno;
string name;
int marks[3];
};
int main()
{
int size = 3;//Extend Size to 25
student s1[size];
for(int i = 0;i <= size-1;i++)
{
cout<<"Enter Details (Roll No, Name and Marks in 3 subjects) of student No "<<(i+1)<<endl;
cin>>s1[i].rollno;
cin>>s1[i].name;//name should have no spaces
for(int j=0;j<=2;j++)
cin>>s1[i].marks[j];
cout<<endl;
}
for(int i=0;i<=size-1;i++)
{
int count = 0;
for(int j=0;j<=2;j++)
{
if(s1[i].marks[j] < 50)//Let Passing marks are 50 out of 100
count++;
}
if(count > 1)
{
cout<<s1[i].rollno<<"\t"<<s1[i].name<<"\t"<<endl;
}
}
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 43

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a;
int *p = &a;
cout<<"Enter the No : ";
cin>>*p;
if(*p == 0)
{
cout<<1;
return 0;
}
for(int i=*p-1 ; i>=1 ; i--)
{
*p = *p * i;
}
cout<<"Factorial is : "<<*p;
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 44
#include <iostream>
#include <conio.h>
using namespace std;
void Display (int *a)
{
for(int i=0;i<=9;i++)
{
cout<<*a<<"\t";
a++;
}
}
int main()
{
int temp,size=10,a[size]={4,19,1,3,3,4,6,6,0,2};
int *p = a;
for(int j=0;j<=size-2;j++)
{
for(int i=0;i<=size-2;i++)
{
if(*p > *(p+1))
{
temp = *p;
*p = *(p+1);
*(p+1) = temp;
}
p++;
}
p = a;
}
cout<<"The elements in the order of increase are : "<<endl<<endl;
Display(p);
getch();
return 0;
}
Mudassir Ahmad : 16PWELE4963
Section “D”
Computer Programming Lab Task 45

#include <iostream>
#include <conio.h>
using namespace std;
int linearsearch(int *x,int size,int key)
{
for(int i=0;i<=size-1;i++)
{
if(key == *x)
return i;
x++;
}
return -1;
}
int main()
{
int size=5,Position,key;
int A[size]={5,3,9,1,23};
cout<<"Enter Search key : ";
cin>>key;
Position=linearsearch(A,size,key);
if(Position == -1)
cout<<"Value not found";
else
cout<<"value founded at index "<<Position;
getch();
return 0;
}

Potrebbero piacerti anche