0% found this document useful (0 votes)
122 views32 pages

Ee 163 Task 21026

This document contains a lab report for computer programming assignments. It discusses 5 tasks completed across 4 lab sessions. The tasks include writing programs to print patterns, calculate averages, solve quadratic equations, and build a basic calculator. Code snippets are provided for each program written. The report analyzes the outputs and explains concepts like Boolean data types, logical operators, and precedence of operations in C++.

Uploaded by

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

Ee 163 Task 21026

This document contains a lab report for computer programming assignments. It discusses 5 tasks completed across 4 lab sessions. The tasks include writing programs to print patterns, calculate averages, solve quadratic equations, and build a basic calculator. Code snippets are provided for each program written. The report analyzes the outputs and explains concepts like Boolean data types, logical operators, and precedence of operations in C++.

Uploaded by

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

COMPUTER

AND
PROGRAMMING

LAB TASK
NAME : MUHAMMAD UZAIR RASHID
ROLL NO.: EE-21026
SECTION: A
DEPARTMENT : ELECTRICAL ENGINEERING
COURSE CODE : EE-163
COURSE INSTRUCTOR : SIR IQBAL AZEEM

Name :
Lab Session 1:
Task 1:

Write a program to print text in following pattern,

Hello World

Hello World Hello


World

#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World \n\tHello World \nHello World";
return 0;
}
Lab Session 2:
EXERSICE:
Identify the data types for the following items
Item Type Item Type
TRUE Boolean @ character
127 Integer 192.12 Floating point
Pakistan string

Task 1:
How to insert single line and multiline comments in a C++ program.
Single line command is insert by using // and continue until the end of line. If the last character in a
comment Line is a \ the comment will continue in the next line .for multi-line comment we use /* at the
start and at the end */. For example: for single line “// single line comment method “and for multiline
comment “/* let us consider the Statement for multi-line.*/”
Task 2:
Variable Declarations can appear almost anywhere in the body of C++ function (T/F).
If true, then discuss the situation in which variable declaration must be done prior to some specific
task. Support you answer by giving example.
variable declaration can almost appear in the body anywhere of c++ function but yes it is also give more
priority in different cases such cases are creating of local function we declared first variable similary in
loops we also declarae variable first.
Task 3:
Calculate the maximum and minimum number that can be accommodated by int data type (calculate
range).
The range of an int data type is -2,147,483,648 to 2,147,483,647.
Task 4:
What do you mean by Variable Declaration and Variable Definition in C/C++?
Declaration of variable is for informing to the compiler the following information : name of the
variable, type of value it hold sad the initial value if any it takes i.e., declaration gives detail about the
properties of a variable. Whereas, definition of a variable says where the variable gets stored .
Task 5:
Check the output of the following cout functions and write your comments.
1. cout << “I am a computer geek, \rits a \blie.”
2. cout <<"a"<<"\t"<<"b"<<"\t"<<"c"<<endl;
1. first program can’t execute because of there is an syntax issue it mean compiler think it will
continue .
2. In second one the program first print “a” the tab and print “b” similarly again tab and Print “c”.
Lab Session 3
EXERSICE:
S.No number1 number2 operation result
1 12 8 + 20
2 12 8 - 4
3 12 8 * 96
4 12 8 / 1
5 12 8 % 4
Now try the following codes

Code 03

1. #include<iostream>
2.
3. using namespacestd;
4.
5. int main()
6. {
7.
8. int number1 = 74, number2 = 82, number3 = 88;
9. double average;
10. average = number1 + number2 + number3 / 3;
11. cout<<average;
12. return 0;
13. }
Code 04

1. #include<iostream>
2.
3. using namespace std; 4.
5. int main()
6. {
7.
8. int number1 = 74, number2 = 82, number3 = 88;
9. double average;
10. average = (number1 + number2 + number3) / 3;
11. cout<<average;
12. return 0;
13. }

 What did you observe from the output of the above two programs? Try to explain briefly.
Code 3 = the result is 185 wrong
Code 4 = the result is 81 correct
The result of first output is wrong because there is no parenthesis used due to which compiler read
program in the Sequential order from left to right so to get the result of higher precedence and wright
result .

Task 1:
Using compound assignment operators, write a program that generates the following output:
x = 2.5 y = 10
x = 25.0 y = 15
x = 250.0 y = 20
x = 2500.0 y = 25
Initialize x as float with value of 2.5 and y as int with value 10. In each successive stage, use *=
operator for x and += operator for y to achieve the desired values.

#include <iostream>using namespace


std;
int main()
{
double x=2.5;
int y=10,counter; for(counter=0;counter<4;counter++)
{
cout<<"\nx="<<x<<"\t\ty="<<y;
x*=10,y+=5;
}
return 0;
}

Task 2:
Write a program that asks the user to enter the length of base and perpendicular of a right angletriangle.
Then it determines the length of hypotenuse, angle between base and hypotenuse and angle between
hypotenuse and perpendicular. Also find the sine and cosine values of these angles. (For hint refer to
basic trigonometry from any mathematics book).
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
float hyp, base, perp, theta1, theta2;
float pie=3.142;
cout<<"Enter perpendicular distance:";
cin>>perp;
cout<<"Enter Base:";
cin>>base;
hyp = sqrt(perp*perp+base*base);
theta1= asin(perp/hyp);
theta2= (pie/2)-theta1;
cout<<"Hypotenuse:"<<hyp<<endl;
cout<<"Angle b/w base and hyp:"<<theta1<<endl;
cout<<"Angle b/w perp and hyp:"<<theta2<<endl;
cout<<"sinθ:"<<perp/hyp<<endl;
cout<<"cosθ:"<<base/hyp<<endl;
return 0;
}

TASK 3:
1. Write a program that asks the user to enter coefficients a, b and c of the stand ard quadratic equation:
ax2+bx+c=0

The program then should compute and display discriminant |b2-4ac|


And the roots of equationFinally, give opinion on how the program could be made more
general to different input conditions
#include <iostream>
#include <cmath> #include<complex>
using namespace std;int main()
{
float a,b,c,x1,x2;
cout<<"ax^2 + bx + c=0"<<endl; cout<<"Enter coefficents of
a,b & c";cin>>a>>b>>c;
double d=(b*b-4*a*c);if(d>=0)
{
x1= -b+sqrt(d)/2*a; x2= -b-sqrt(d)/2*a;
cout<<"x1"<<x1<<endl;
cout<<"x2"<<x2<<endl;
}
else
{
double sqrt_d = sqrt(-d)double real = -b/2*a;
double imag = sqrt_d/2*a;
complex<double>x1 = complex<double>(real,imag); complex<double>x2 =
complex<double>(real,imag);cout<<"x1="<<x1<<endl;
cout<<"x2="<<x2<<endl;
}
return 0;
}
Lab Session 4
Code 01

1. #include<iostream>
2. using namespace std; int main(void)
3. {
4. int num1=105, num2=34;
5. float pi=3.1412, x=123.5;
6. string password="abcd1234";
7. bool result=(num1>num2);
8. cout<<num1<<">"<<num2<<"\t1=true, 0=false";
9. cout<<"\nanswer="<<result<<endl;
10. cout<<pi<<"="<<x<<"\t1=true, 0=false";
11. cout<<"\nanswer="<<(pi==x)<<endl;
12. cout<<"Is the password correct?\t1=yes, 0=no";
13. cout<<"\nanswer="<<(password=="abcd1234");
14. return 0;
15. }

 What did you understand from the results of above program?


The above program shows Boolean data type .If statement containing relational operation and correct
and true true it will print 1 . If false then it will print 0.

Code 02

1. #include<iostream>

2. using namespace std;

3. int main(void)
4. {
5. bool a=true, b=0, c=0, result;
6. result=(c||a);
7. cout<<"a AND b="<<(a&&b);
8. cout<<"\nc OR a="<<result;
9. cout<<"\nNOTa="<<(!a);
10. cout<<"\nNOTb="<<(!b);

11. cout<<"\nNOTc="<<(!c);

12. return 0;
13. }

 Explain in few lines what you understood from the above program
The program shows Boolean data type logical operators like AND, OR, NOT are used if the output is 1
means its true and if it false mean 0.
Code 03

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

{ //Calculator Program double operand1, operand2, result; char operation;


cout<<"\t***Calculator Program***";
cout<<"\nEnter the desired expression"<<"with spaces<eg 12.6 + 4.32>";
cin>>operand1>>operation>>operand2;
if(operation=='+')
{
result=operand1+operand2;
}
if(operation=='-')
{ result=operand1- operand2;
}
if(operation=='*')
{
result=operand1*operand2;
}
if(operation=='/')
{
result=operand1/operand2;
}
if(operation!='+' || operation!='-' || operation!='*'|| operation!='/' )
{ cout<<"\nInvalid Operator";
}
cout<<"\n\nresult="<<result;

return 0;
}

 What did you understand from the results of above program?


This is a calculator program that only uses operations like ‘+’, ‘-‘, ‘*’, ‘/’. If the program uses operations
other then that Console output is supposed to show “invalid operator ”. But the logical operator “OR” is
used for this purpose and it Gives “Invalid Operator” if we replace ‘+’, ‘-‘, ‘*’, ‘/’we replace “OR” with
“AND” to get the desire output.
TASK 1:
Write a program that asks user to enter 3 numbers and then finds the largest and smallest among
them and displays both largest and smallest number. This program can be written in many ways.
Provide at-least two methods.
#include<iostream> using
namespace std;int main()
{
int a,b,c,smallest,largest;cout<<”Enter
a,b and c”; cin>>a>>b>>c;
largest=a; if(largest<b)
{
largest=b;
}
if(largest<c)
{
largest =c;
}
smallest =b; if(smallest>a)
{
smallest=a;
}
if(smallest>c)
{
smallest=c;
}
cout<<”Largest”<<largest<<endl; cout<<”Smallest”<<smallest<<endl;
}
METHOD 2:
#include <iostream>using
namespace std;int main()
{
float a,b,c, large,small; cout<<"Enter
value of a";cin>> a;
cout<<"Enter value of b";cin>> b;
cout<<"Enter value of c";cin>>c;
if(a>b && a>c)
{
large=a;
if(b<c)
{
small=b;
}
if(c<b)
{
small=c;
}
}
else if(b>a && b>c)
{
large=b;
if(a<c)
{
small=a;
}
if(c<a)
{
small=c;
}
}
else
{
large=c;
if(a<b)
{
small=a;
}
if(b<a)
{
small=b;
}
}
cout<<"Largest Number is"<<large<<endl;
cout<<"Smallest Number is"<<small<<endl;
return 0;
}
TASK 2:
C++ provides an alternate approach for if () – else if () statements, that is switch () – case
statement. Use literature and internet resources to understand using it. Then write a calculator
program written in lab session using switch ()-case statements. If the user entered the operator
other than +,-,*,/ then program should print “Invalid Operator” on screen.
#include <iostream>
using namespace std;
int main(void)
{
char operation;
double operand1,operand2; cout<<"Enter operation with spaces";
cin>>operand1>>operation>>operand2;switch(operation)
{
case'-':
cout<<operand1<<""<<operation<<""<<operand2<<"="<<operand1- operand2;
break;
case'*':
cout<<operand1<<""<<operation<<""<<operand2<<"- "<<operand1*operand2;
break;
case'+':
cout<<operand1<<""<<operation<<""<<operand2<<"="<<operand1+oper and2;
break;
case'/':
cout<<operand1<<""<<operation<<""<<operand2<<"="<<operand1/oper and2;
break; default:
cout<<"Invalid operation";
break;
}
}
Lab Session 5
Code 01:

#include<iostream>
using namespace std;
int main(void)
{
int num;
for(int num=0;num<=10;num++)
{
cout<<"\n num = "<<num;
}
return 0;
}

 Observe the output of this program and describe in your words;


This program contain “for” loop. First there is initializations then conditioned testing and at last
increments. The output Contain 11 ilteration from 0 to 10 number because condition say “less than
equal to” 10.
Code 03

#include<iostream>
using namespace std;
int main(void)
{ // 10x10 Grid of a character
int row,col;
char display_char;
cout<<"Enter a character for display:";
cin>>display_char;
cout<<endl<<endl;
for(int row=1;row<=10;row++)

{
for(int col=1;col<=10;col++)
{
cout<<display_char;
}
cout<<endl; }
return 0;
}

Draw output here

Code 04

#include<iostream> using
namespace std;
int main() {
for(int row = 1; row <= 5; ++row)
{ for(int col = 1; col <= 5; ++col)
{ cout<<row<<" * "<<col<<" = "
<<row * col<<"\t";
}
cout<<endl;
}
}

Draw the output here


Exercise

Task 1:
Write a program to print following pattern using for loops (do not use if, if-else or any other decision
making statement).

a) *

***

*****

*******

b) 1
121

12321

1234321

#include <iostream>

using namespace std;

int main()
{
int stars = 1;
int spaces = 4;
for(int x = 0; x <=3; x++){ // This values "x <= 3 " defines no of
rows of stars.
for(int y =0; y < spaces; y++){
cout <<" ";
}
for(int z = 1; z <= stars; z++){
cout << "*";
}
cout << endl;
stars+=2;
spaces--;
}
}

#include <iostream>

using namespace std;

int main()
{
int a,b,c;
c = 1;
for(a = 1; a<=4; a++){

for(b = 1; b <=4-a; b++)


{
cout <<" ";
}
for(b = 1; b <= a ; b++){
cout <<b;
}
for(b =a-1; b>=1; b--)
{
cout <<b;
}
cout << endl;
}
return 0;
}
Task 2:
Using for() loops, write a program that displays all possible combination of 6 bit binary number. (Hint:
You shall need 6 int variables for the six digits)

Sample Run: 000000, 000001, 000010, 000011, ........................111111

#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f;
for(a = 0 ; a <=1 ; a++)
{
for(b=0 ; b <= 1 ; b++)
{
for(c=0 ; c <=1 ; c++)
{ for(d=0 ; d<=1 ; d++)
{
for(e=0 ; e<=1 ; e++)
{ for(f=0 ; f<=1 ; f++)
{
cout << " " << a << b << c << d << e << f<<" , ";}}}}}}

return 0;

}
Lab Session 6

Code 01

#include<iostream>
#include<conio2.h> using
namespace std; int
main(void)

{ char guess; cout<<"Press any key


from keyboard :"; cout<<"\n This
program shall end only" <<" when
you press the secret key";
guess=getche(); while( guess!='x' )

{ cout<<"\n Wrong input, try another


key:"; guess=getche();

} cout<<"\nEureka! You have discovered


it."; getch();

return 0;

 Observe the output of this program and describe in your words


Program repeatedly asked input “x” is entered a the secret key . on entering ‘
x’ it shows “Eureka! You have discovered it.”

Exercise

Task 1:
Write a program that continuously asks user to enter an integer and displays the SUM of the current
input with all previous input. The program continuous to run until the SUM value is less than equal to
100. Use while() loop.
Sample Run:
Enter an integer: 12 [Enter]
Running Sum = 12

#include<iostream>
using namespace std;
Enter an integer: 10 [Enter]
int main(void)
Running Sum = 22
{

Enter an integer:70 int num,running_sum=0;


Running Sum = 92 cout<<"Enter an integer:";
[Enter]
.
cin>>num;
. running_sum=running_sum+num;
. while(running_sum<=100)
Sum exceeds 100. {
Program
terminated. cout<<"Running sum="<<running_sum<<endl;

cout<<"\nEnter an integer:";

cin>>num;

running_sum=running_sum+num;

cout<<"\nSorry. Your running sum exceeded 100.";

Task 2:
Write a program that counts number of digits in an integer entered by the user. Use while() loop.

Sample Run:
Enter an integer: 123456 [Enter]

No. of digits = 6

#include<iostream>

using namespace std;

int main()

//write a program that counts number of digits in an integer entered by the user using while loop.
int num1, num2;

int count = 0;

cout<<"Enter the number: ";

cin>> num1;

num2=num1;

while(num2 != 0)

count++;

num2 /= 10;

cout<<endl<<"Total digits in " << num1 <<" : "<< count;

return 0;

return 0;

}
Lab Session 7
Exercise:

Task 1:
Halley’s Method for Determination of roots of polynomial is

Write a program to find roots of the following polynomial using Halley’s method, precision is 0.0001

(𝑥) = 𝑎𝑥3 + 𝑏𝑥2 + 𝑐𝑥 + 𝑑


#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int a,b,c,d;
float xn;
double fxn,fpxn,fdxn,lng;
cout<<"enter the values of coefficients of the equation"<<endl;
cin>>a>>b>>c>>d;
cout<<"equation is"<<endl;
cin>>lng;
xn=lng/2;
fxn=(a*xn*xn*xn)+(b*xn*xn)+(c*xn)+d;
fpxn=(3*a*xn*xn)+(2*b*xn)+c;
fdxn=(6*a*xn)+(2*b);
while(fabs((2*fxn*fpxn)/((2*pow(fpxn,2))-(fxn*fdxn)))>0.0001)
{
fxn=(a*xn*xn*xn)+(b*xn*xn)+(c*xn)+d;
fpxn=(3*a*xn*xn)+(2*b*xn)+c;
fdxn=(6*a*xn)+(2*b);
xn=xn-(2*fxn*fpxn)||((2*pow(fpxn,2))-(fxn*fdxn));
}
cout<<"the roots of the equation are"<<xn;
return 0;
}
Q2: Write an iterative algorithm to implement the following expansion (precision upto 0.0001)

#include <iostream>
using namespace std;
double radians(double degrees) // converts degrees to radians
{
double radians; double const pi = 3.14159265358979323846;
radians = (pi/180)*degrees; return radians;
}
double factorial(int x) //calculates the factorial
{
double fact = 1;
for( int x ; x>=1 ; x-- )
{
fact = x*fact;
}
return fact;
}
doule power (double x, double n)
{
double output = 1;
while(n>0)
{
output = x*output;
n--;
}
return output;
}
float sin(double radians)
{
double a,b,c;
float result = 0;
for(int y = 0; y != 9 ; y++)
{
a = power(-1,y);
b = power(radians,(2*y)+1);
result = result + (a*b)/c;
}
return result;
}
double n, output;
int main()
{
cout<<"Enter the value\t";
cin>>n;
n = radians(n);
cout<<"\nthe value in radians is\t"<<n<<"\n";
output = sin(n);
cout<<"\nsine of the given value is\t"<<output;
return 0;
}
Lab Session 8
Read in 20 numbers in an array, each of which is in between 10 and 100 – if the number is not in this
range, ask user to re-enter. As each number is read by the program, print it only if it is not a duplicate
of a number already read.

#include <iostream> #define SIZE 20 using namespace std;


void checkIfExists(int b[], int index)
{
int i, j, flag = 0;
for (i = 0; i < index; i++)
{
if (b[index] == b[i])
{
return;
}
}
cout <<b[index]<< " ";
}
int main()
{
int i;
int numArray[SIZE] = { 0 };
cout << "Enter "<<SIZE<<" numbers: "; for (i = 0; i < SIZE; i++)
{
cin >> numArray[i];
}
for(i=0;i<SIZE;i++)
{
if(numArray[i]>=10 && numArray[i]<=100)
{
cout << "You input: \n"; for (i = 0; i < SIZE; i++)
{
cout <<numArray[i]<<" ";
}
cout << "\n";
cout << "The nonduplicate values are: \n"; cout << numArray[0]<<" ";
for (i = 1; i < SIZE; i++)
{
checkIfExists(numArray, i);
}
}
else
{
cout << "\n\nPlease input in range between 10 to 100 only "; break;
}
}
return 0;
}

TASK 2:
Write a simple database program that stores name, roll no., and cgpa in FE , all in separate arrays,
for 25 students. The program should be able to let the user enter records, display records and replace
any one of the records (switch()-case can be used to give these options to user). The program must
continue until ESC is pressed. [Note: A single ‘record’ means name, roll no., and cgpa of one student].

#include <iostream>
using namespace std;
int main()
{
int roll[25];
string name[25];
float cgpa[25];
int n;
do
{

cout<<endl<<"Menu"<<endl<<"1-Enter records"<<endl<<"2-Display Records"<<endl<<"3-Replace


Records"<<endl<<"0-Exit";
cin>>n;
switch(n)
{
case 1:
for(int i=0; i<25; i++)
{
cout<<endl<<"Enter the name of student "<<i+1<<" : ";
cin>>name[i];
cout<<endl<<"Enter the GPA of student "<<i+1<<" : ";
cin>>cgpa[i];
cout<<endl<<"Enter the roll number of student"<<i+1<<" : ";
cin>>roll[i];
}
break;
int number;
case 2:
cout<<endl<<"Enter the roll number to display the record of the student:";
cin>>number;
for(int i=0; i<25; i++)
{
if(number == roll[i])

{
cout<<endl<<"Name: ";
cout<<name[i];
cout<<endl<<"Roll Number: ";
cout<<roll[i];
cout<<endl<<"Name:";
cout<<cgpa[i];
}
else
{
if(i<25)
{
continue;
}
else{
cout<<"Record not found!";
}
}
}
break;
case 3:
cout<<"Enter the roll number to replace the student details: ";
cin>>number;
cout<<endl<<endl<<"Replacing the Details......";
for(int i =0; i<25; i++)
{
if(number == roll[i])
{
cout<<endl<<endl<<"Replacing the details......";
cout<<endl<<"Name: ";
cin>>name[i];
cout<<endl<<"GPA: ";
cin>>cgpa[i];
}
else
{
if(i<25)
{
continue;
}
else{
cout<<"Record not found!";
}
}
}
break;
}
} while(n!=0);
return 0;}
Lab session 9
Exercise:
TASK 1:
Write program with a function that accepts 3 int type numbers and returns the smallest among them.
The function is called minimum().

#include <iostream>
using namespace std;
int minimum(int a, int b, int c);
int a,b,c;
int main (void)
{
int a,b,c;
cout<<"Enter the three integers ";
cin>>a>>b>>c;
cout<<"The smallest or minimum number is "<< minimum( a, b,c);
return 0;
}
int minimum (int a, int b, int c)
{
if(a<b && a<c)
{
return a;
}
else if(b<a && b<c)
{
return b;
}
else(c<a && c<b);
{
return c;
}
}
TASK 2:
Write a void function that generates a precise delay of 2 seconds whenever it is called. The
function should contain clock() function or time() function from ctime, for precise timing.

#include <iostream>
#include <ctime>
using namespace std;

void sleep(float seconds)


{
clock_t startClock = clock();

float secondsAhead = seconds * CLOCKS_PER_SEC;

// do nothing until the elapsed time has passed.

while(clock() < startClock+secondsAhead);


return;
}
int main(){

cout << "Next string coming up in two second delay!" << endl;

sleep(2.0);

cout << "Hey, what did I miss?" << endl;

return 0;
}
Lab session 10
Exercise:

TASK 1:
Write a recursive function to implement Newton Raphson Method algorithm to determine square root
of a number.

#include<cmath>
using namespace std;
float N,low,high,root;
float square_root(float root);
int main(void)
{
cout<<"Enter a +ve number to calculate its square root:";
cin>>N;
cout<<"\n square root of "<<N<<" = "<<square_root(root);
return 0;
}
float square_root(float root)
{
if(N<0)
{
return 0;
}
else
{
root=N/2.0;
while(fabs(((root*root)-N))>0.0001)
{
root=root-((root*root-N)/(2.0*root));
}}
return root;}
TASK 2:
Write a recursive function to find Greatest Common Divisor of two numbers using Euclid
Remainder Algorithm.

#include<iostream>

#include<conio.h>

#include<stdlib.h>

using namespace std;

int gcd(int u, int v)


{
return (v != 0) ? gcd(v, u % v) : u;
}
int main(void)
{
int number1, number2, result;
cout <<"Enter two numbers to find GCD using Euclidean algorithm: ";
cin >> number1 >> number2;
result = gcd(number1, number2);

if (gcd)
cout << "\nThe GCD of " << number1 << " and " << number2 <<"is: "<< result<< endl;

else
cout << "\nInvalid input!!!\n";

return 0;
}

You might also like