0% found this document useful (0 votes)
21 views44 pages

PF Manual Muhammad Uzair 64498

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)
21 views44 pages

PF Manual Muhammad Uzair 64498

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/ 44

Laboratory Workbook

Programming Fundamentals
Na me : M u h a mma d Uzair

Registration id : 64498

P r o g ra m : c y b e r s e c u r i ty

Sir : Muhammad Taha


Table of Contents
Experiment 1 .......................................................................................................................................................................10
Exercise............................................................................................................................................................................10
Assignment ......................................................................................................................................................................12
Experiment 2 .......................................................................................................................................................................13
EXERCISE ..........................................................................................................................................................................14
Assignment ......................................................................................................................................................................14
Experiment 3 .......................................................................................................................................................................15
EXERCISES ........................................................................................................................................................................17
Assignment ......................................................................................................................................................................17
Experiment 4 .......................................................................................................................................................................18
Example ...........................................................................................................................................................................18
Assignment ......................................................................................................................................................................18
Experiment 5 .......................................................................................................................................................................21
Exercise............................................................................................................................................................................23
Assignment ......................................................................................................................................................................24
Experiment 6 .......................................................................................................................................................................27
Objective .........................................................................................................................................................................27
Exercise............................................................................................................................................................................29
Assignment ......................................................................................................................................................................32
Experiment 7 .......................................................................................................................................................................36
Example ...........................................................................................................................................................................36
Assignment ......................................................................................................................................................................38

Experiment 1
Objective
Getting familiar with the IDE and working with Turbo C &Microsoft Visual Studio. Installing and copying the compiler,
changing directory settings. Making first program in C. Saving / copying files to USB or other storage devices. Theory

IDE
An integrated development environment (IDE) is a software suite that consolidates the basic tools developers need to write
and test software. Typically, an IDE contains a code editor, a compiler or interpreter and a debugger that the developer
accesses through a single graphical user interface (GUI). An IDE may be a standalone application, or it may be included as
part of one or more existing and compatible applications.

Example Program
Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr(); printf("My First My First Program
Program"); getch();
}

Exercis
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
printf("My First Program");
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
getch();
printf("My First Program");
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
getch();
printf("My First Program");
getch();
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
getch(); clrscr();
printf("My First Program");
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
getch(); printf("My First
Program"); clrscr();
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
getch();
clrscr();
printf("My First Program");
getch();
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
getch();
printf("My First
Program"); getch();
clrscr();
}

Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
getch();
printf("My First Program");
getch();
}
#include<conio.h>
#include<stdio.h>
void main(void)
{ clrscr(); printf("My
First Program"); getch();
}

#include”conio.h”
#include”stdio.h”
void main(void)
{
clrscr();
printf("My First Program");
getch();
}
#include<conio.h>
#include<stdio.h>
main()
{
clrscr();
printf("My First Program");
getch();
}

#include<CONIO.H>
#include<STDIO.H>
void main(void)
{ clrscr(); printf("My
First Program"); getch();
}

Assignment
□ Write a C program using commands described in this lab to make a resume showing your complete details.

#include <stdio.h>
#include<conio.h>
void main()
{
printf("Name:Muhammad Haroon \n");
printf("Address: DHA, karachi\n");
printf("Phone: +03172402969 \n");
printf("Email:muhammad@iqra.edu.pk \n\n");
printf("Education:\n");
printf(" Bachelor of Science in Computer Science\n");
printf(" Iqra University\n\n");
printf("Work Experience:\n");
printf("2 years experience on freelancing\n");
printf(" Student\n\n");
printf("Skills:\n");
printf(" - Programming Languages: C, C++\n"); printf("
- Problem Solving and Algorithm Design\n\n");
printf("Projects:\n");
printf(" DLD LAB: PIR sensor based security system\n");
_getch();
}
OUTPUT:
Experiment 2
Objective
Understanding and Using format specifier and escape sequences with printf.
Theory
The C library functionprintf() sends formatted output to stdout.Following is the declaration for printf() function.

int printf(const char *format, ...)

format − This is the string that contains the text to be written to stdout. It can optionally contain embedded format tags
that are replaced by the values specified in subsequent additional arguments and formatted as requested.

Format specifiers are used to substitute and print values inside a printf or scanf statement which are further applicable on
variables. Below is a chart of format specifier examples using printf.

No. Type Syntax Value Example


1 Single Character %c One character within single quotes printf(“%c”,‟a‟);
2 String %s A sentence of an unfixed length within double quotes printf(“%s”,”Iqra Univ”);
3 Decimal Integer %d Any whole number between -32,768 to 32,767 printf(“%d”, 12345);
4 Long Integer %ld Any number between -2,147,483,648 to 2,147,483,647 printf(“%ld”,1234567);
5 Float %f Any decimal point number between 1 0-38 to 1 038 printf(“%f”, 1234.567);
6 Double %lf Any decimal point number between 10-308 to 10 308
printf(“%lf”,12345678);
Escape Sequences are used to adjust spacing between lines or characters or the characters themselves.

No. Syntax Application Example


1 \n New Line printf(“\n”);
2 \t Tab eight spaces to right printf(“\t”);
3 \b Back space One space back printf(“\b”);
4 \r Carriage return Start of same line printf(“\r”);
5 \‟ Printing single quote printf(“\‟”);
6 \” Printing double quotes printf(“\””);
7 \\ Printing back space printf(“\\”);
8 \xdd Printing characters by Hexa decimal ASCII value printf(“\x45”);
9 \ddd Printing characters by decimal ASCII value printf(“\d45”);

Example
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ A
clrscr(); Iqra University
printf("\n%c",'a'); 20
printf("\n%s","Iqra University"); 35.5
printf("\n%d",20); 1234567
printf("\n%f",35.5); pri
ntf("\n%ld", 1234567);
getch();
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr(); printf("\n%c %s %d %f
%ld",'a',"Iqra A Iqra University 2035.5 1234567
University",20,35.5,134567);
getch();
EXERCISE:

Write the output for following programs and give reasons.


Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr();
printf("\n%d",'a');
printf("\n%s","Iqra University");
printf("\n%c",20);
printf("\n%f",35.5); pri
ntf("\n%ld", 1234567);
getch();
}

Assignment
• Write a C program to make your resume with format specifiers and escape sequences showing your complete
details.
• #include <stdio.h>
#include<conio.h>
void main()
{
printf("************ Resume ************\n\n");
printf("Name:\t\t\Muhammad Haroon \n");
printf("Address:\t\DHA, karachi\n");
printf("Phone:\t\t\t03172402969 \n");
printf("Email:\t\t\muhamad@iqra.edu.pk \n\n");
printf("************ Education ************\n\n");
printf("Degree:\t\t\tBachelor of Science in Computer Science\n");
printf("School:\t\t\tIqra University\n");
printf("************ Work Experience ************\n\n");
printf("\t\t2 years experience on freelancing \n");
printf("\t\tStudent\n");
printf("************ Skills ************\n\n");
printf("Programming Languages:\tC, C++, javascript\n");
printf("Skills:\t\t\tProblem Solving, Algorithm Design\n\n");
printf("************ Projects ************\n\n");
printf("Project:\t\tPIR Sensor based security system\n\n");
printf("************ End of Resume ************\n");
_getch();

• Write a program using escape sequence to produce following output.


#include <stdio.h>

int main() {
printf("Create a new line.\n");
printf("Print a double quote (\") within a string.\n");
printf("Print a single quote (') within a string.\n");
printf("Print a Backslash\\ within a string.\n");
printf("Using Backspace\b within a string.\n");
printf("Using\tTab within a string.\n");

return 0;
}
Theory
Variables are declared by first writing data types followed by a variable name, e.g. int a=10;

Here

int is data type, a is variable name


and after the equals to sign (=) is the value in it 10 the value is always followed by a terminator(;)

No. Data Type Syntax Supported Value Example


format
Specifier
1 Single Character char %c One character within single quotes char a=‟a‟;
2 Decimal Integer int %d Any whole number between -32,768 to 32,767 int a=10;
3 Long Integer long int %ld Any number between -2,147,483,648 to 2,147,483,647 long int a=12345;
4 Float float %f Any decimal point number between 10-38 to 1038 float a=1234.567;
5 Double double %lf Any decimal point number between 1 0-308
to 10308
double a=1 23456;
Variable Names
Variable names will always start with an alphabet.
Variable names can contain numbers (1,2,45,66) and underscores (_) but no other special characters
(!@#$%^&*). Variable names cannot resemble to any predefined word e.g. include, printf, getch, scanf etc.. A
variable name cannot be used for multiple declarations.

Example
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr();

char a='a'; int a 12 12.5 1234567


b=12;
float c=12.5; double
d=1234567;
printf("%c %d %f %lf",a,b,c,d); getch();
}

#include<stdio.h>
#include<conio.h> void
main(void)
{ clrscr(); char
a='a',a1=’b’;

int b=12,b1=13; float c=12.5,c1=13.5; b 13 13.5 1234568


double d=1234567,d1=1234568;
printf("\n%c %d %f %lf",a,b,c,d);
printf("\n%c %d %f %lf",a1 ,b1
,c1,d1); getch();
}
EXERCISES:
Write the output for following programs.
Program Output
#include<stdio.h>
#include<conio.h
> void main(void)
{ clrscr(); char
a=97; int b=’A’;
float c=12.5;
double
d=1234567;
printf("%c %d %f %lf",a,b,c,d);
getch();
}

Assignment
Write a C program to declare multiple variable that shows an employee details such as Name, age, phone no, salary
address and designation. The program should print details of employee.
#include <stdio.h>
int main() {
char name[50]
="Haroon”;
int age = 20;
long long phoneNumber =172402969
; double salary = 56000;
char address[100] = "DHA ,karachi";
char designation[50] = "programmer";
printf("Employee Details:\n");
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Phone Number: %lld\n", phoneNumber);
printf("Salary: $%.2lf\n", salary);
printf("Address: %s\n", address);
printf("Designation: %s\n", designation);
return 0;
}
22

Experiment 4

Objective
Taking Input from the user at console screen using scanf and getche commands.

Theory
Scanf command can take input of different data types at a time.
Getche command can take only one character input.

Example
Write the output after supplying appropriate input on console screen.
Program Output
#include<stdio.h>
#include<conio.h
> void main(void)
{
clrscr();
char a;
int b;
float c;
double
d;
printf("\nEnter character ");
scanf("%c",&a);
printf("\nEnter integer ");
scanf("%d",&b);
printf("\nEnter float ");
scanf("%f",&c); printf("\nEnter
double "); scanf("%lf",&d);
printf("\n%c %d
%f
%lf",a,b,c,d); getch();
}
#include<stdio.h>
#include<conio.h
> void main(void)
{
clrscr();
char a;
int b;
float c;
double
d;
printf("Enter char integer float
double\n"); scanf("%c %d %f
%lf",&a,&b,&c,&d); printf("\n%c %d %f
%ld",a,b,c,d); getch();
}

#include<stdio.h>
#include<conio.h
> void main(void)
{ clrscr(); pri ntf("\nWhat is your
section : "); getche();
getch();
}

Assignment
Write a C program that takes input from the user and then displays the complete details such as his name, course, university,
program and location.
#include <stdio.h>
int main() {
18
char name[50], course[50], university[50], program[50], location[50];
printf("Enter your name: ");
scanf("%49[^\n]", name);

printf("Enter your course: ");


scanf(" %[^\n]", course);

printf("Enter your university: ");


scanf(" %[^\n]", university);

printf("Enter your program: ");


scanf(" %[^\n]", program);

printf("Enter your location: ");


scanf(" %[^\n]", location);
printf("\nComplete Details:\n");
printf("Name: %s\n", name);
printf("Course: %s\n", course);
printf("University: %s\n", university);
printf("Program: %s\n", program);
printf("Location: %s\n", location);

return 0;
}
Write a C program that takes two numbers as input and swap their values .

20
Experiment 5
Objective
Arithmetic operators, conditional operators, assignment operators, Increment/decrement operators.Studying Math
functions.

Theory
Math.h header file is included for the definitions of math functions listed below. It is written as #include<math.h>.

Example
The program below shows the result for math and trigonometric functions. The functions pass the values to variables which
are further used for printing in printf.
Program
Output
#include<stdio.h>
#include<conio.h>
#include<math.h> void
main(void)
{ clrscr();
float a=45,b=1,sn,cs,tn,snh,csh,tnh; sn=sin(a);

cs=cos(a); Trignometric
Functions
sin 45 = 0.85 cos
tn=tan(a); 45 = 0.53
snh=sinh(b); csh=cosh(b); tan 45 = 1.62

tnh=tanh(b);
Hyperbolic Functions
printf("\n\n\n Trignometric Functions"); sinh 1 = 1.18
printf("\nsin 45 = %.2f",sn); cosh 1 = 1.54
printf("\ncos 45 = %.2f",cs); tanh 1 = 0.76
printf("\ntan 45 = %.2f",tn);
printf("\n\n\n Hyperbolic Functions");
printf("\nsinh 1 = %.2f",snh);
printf("\ncosh 1 = %.2f",csh);
printf("\ntanh 1 = %.2f",tnh); getch();
}
The program below shows the result for math and trigonometric functions. It also demonstrates that some functions may be
called within the body of another function. For example here all the trigonometric functions are called inside printf function.

Program Output
#include<stdio.h>
#include<conio.h>
#include<math.h>

void main(void) Trignometric Functions


{ sin 45 = 0.85
clrscr(); printf("\n\n\n Trignometric cos 45 = 0.53 tan
45 = 1.62
Functions"); printf("\nsin 45 =
%.2f",sin(45));

printf("\ncos 45 = %.2f",cos(45)); Hyperbolic Functions


printf("\ntan 45 = %.2f",tan(45)); sinh 1 = 1.18
cosh 1 = 1.54
printf("\n\n\n Hyperbolic Functions"); tanh 1 = 0.76
printf("\nsinh 1 = %.2f",sinh(1));
printf("\ncosh 1 = %.2f",cosh(1));

printf("\ntanh 1 = %.2f",tanh(1)); Math Functions pow


2,3 = 8.00
printf("\n\n\n Math Functions"); sqrt 49 = 7.00
printf("\npow 2,3 = %.2f",pow(2,3));
printf("\nsqrt 49 = %.2f",sqrt(49));
getch();
}

Operators

Arithmetic Relational Assignment Increment/decrement operators


operators operators operators
Add + Greater Than > Addition assignment += Increment ++
Subtract - Less Than < Subtraction assignment -= Decrement -- Multiplication * Greater or Equal >= Multiplication assignment
*=

RemainderDivision %/ Less or EqualEqual EqualNot Equal <===!= Division assignment /=


22
Example
Explain the following program after careful study.
Program Output
#include<stdio.h> #include<conio.h>
main()
{ clrscr();

int a=2,b=4,c1,c2,c3,c4,d1,d2,d3,d4; 6 -2 8 0
c1=c2=c3=c4=5; 010101
d1=d2=d3=d4=8; 8 2 15 1
printf("\n%d %d %d %d",a+b,a-b,a*b,a/b); 8987
printf("\n%d %d %d %d %d %d",a>b,a<b,a>=b,a<=b,a==b,a!=b);
printf("\n%d %d %d %d",c1+=3,c2-=3,c3*=3,c4/3); printf("\n%d
%d %d %d",d1++,++d2,d3--,--d4); getch();
}

Exercise
Write output for following programs and give reasons.
Program Output
#include<stdio.h>
#include<conio.h
> main()
{
clrscr(); int a=5;
printf("\n%d
%d",a++,a);
printf("\n%d
",a);
getch();
}

#include<stdio.h>
#include<conio.h
> main()
{
clrscr(); int a=5;
printf("\n%d
%d",++a,a);
printf("\n%d
",a);
getch();
}

#include<stdio.h>
#include<conio.h
> main()
{
clrscr(); int a=5;
printf("\n%d
%d",a - -,a);
printf("\n%d
",a); getch();
}

Program Output
#include<stdio.h>
#include<conio.h>
main()
{
clrscr(); int
a=5; printf("\n%d
%d",- - a,a);
printf("\n%d ",a);
getch();
}
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a=5;
printf("\n%d %d %d %d",a++,++a,a,a
- -); printf("\n%d ",a); getch();
}

#include<stdio.h> #include<conio.h>
main()
{
clrscr(); int a=5; printf("\n%d %d
%dd",a+5,++a,a);
printf("\n%d ",a);
getch();
}

#include<stdio.h>
#include<conio.h>
main()
{
clrscr(); int a=5; printf("\n%d %d
%dd",a+=5,++a,a);
printf("\n%d ",a);
getch();
}

#include<stdio.h>
#include<conio.h>
main()
{
clrscr(); int a=5; printf("\n%d %d
%dd",a-=5,- -a,a);
printf("\n%d ",a);
getch();
}

#include<stdio.h> #include<conio.h>
main()
{
clrscr(); int a=5; printf("\n%d %d
%dd",a+=5,a++,a);
printf("\n%d ",a);
getch();
}

Assignment

1. Program the following.


Implement the following equation
3x4sin(180x) + 4x3 cos(90x) + x2sin(tan(45)) + 7x + 9cos(90x2 )

where x may be user defined value.

24
#include <stdio.h>

#include <math.h>

int main() {

double x;

printf("Enter the value of x: ");

scanf("%lf", &x);

double result = 3 * pow(x, 4) * sin(180 * x) + 4 * pow(x, 3) *

cos(90 * x) + pow(x, 2) * sin(tan(45)) + 7 * x + 9 * cos(90 * pow(x, 2));

printf("Result of the equation for x = %.2f: %.4f\n", x, result);

return 0;

2. Program the following.


• Prompt user to input distance in Kilometers and display it in meters.
• Input any number from user and generate its square e.g. square of 8 is 64
• Input any number from user and generate its cube e.g. cube of 8 is 512
• Input a 4 digit number in any integer type variable and sum all the four digits, e.g. int a =3487, result = 22
Generate the table for a number input by the user.
• For the following equation 3x4 + 4x3 + x2 + 7x + 9, substitute the user provided value of x and generate the
result.
#include
<stdio.h> #include
<math.h> int
main() {
// Prompt user to input distance in Kilometers and display it in
meters double distanceInKilometers;
printf("Enter distance in Kilometers: ");
scanf("%lf", &distanceInKilometers);
double distanceInMeters = distanceInKilometers *
1000; printf("Distance in Meters: %.2f\n\n",
distanceInMeters);

// Input any number from the user and generate its


square int numSquare;
printf("Enter a number to calculate its square:
"); scanf("%d", &numSquare);
int squareResult = numSquare * numSquare;
printf("Square of %d is %d\n\n", numSquare, squareResult);

// Input any number from the user and generate its


cube int numCube;
printf("Enter a number to calculate its cube:
"); scanf("%d", &numCube);
int cubeResult = numCube * numCube * numCube;
printf("Cube of %d is %d\n\n", numCube,
cubeResult);

// Input a 4-digit number and sum all the four


digits int fourDigitNumber;
printf("Enter a 4-digit number:
"); scanf("%d",
&fourDigitNumber);
int digitSum = (fourDigitNumber / 1000) + ((fourDigitNumber / 100) % 10) + ((fourDigitNumber / 10) % 10) +
(fourDigitNumber % 10);
printf("Sum of digits: %d\n\n", digitSum);

// Generate the table for a number input by the


user int tableNumber;
printf("Enter a number for the table: ");
scanf("%d", &tableNumber);
printf("Table for %d:\n",
tableNumber); for (int i = 1; i <= 10;
++i) {
printf("%d x %d = %d\n", tableNumber, i, tableNumber * i);
}
printf("\n");

// For the equation 3x^4 + 4x^3 + x^2 + 7x + 9, substitute the user-provided value of x and generate the
result double xValue;
printf("Enter a value for x: ");
scanf("%lf", &xValue);
double equationResult = 3 * pow(xValue, 4)+ 4 * pow(xValue, 3) + pow(xValue, 2) + 7 * xValue + 9;
printf("Result of the equation for x = %.2f: %.4f\n", xValue,
Experiment 6
Objective
Studying loops. For loops, nested for loops, while loops, nested while loops, do while loops, nested do while loops. Studying
loops with cross combination.
Theory
for while do while
initialization initialization; do
; {
for(initialization ; check range ; iteration) body
{ while(check
range) iteration;
body } while(check range)
{
} body
iteration;
}
Example: This table below shows nested loops. All the three programs have same output.

Loop Nested
Program Output Program Output
Loop
#include<stdio.h> 03
#include<conio.h> 13
void main(void) 23
{ 33
#include<stdio.h> clrscr();
#i nclude<conio. for(int a=0;a<=3;a++)
h>void main(void) {
{ for(int b=0;b<=3;b++)
clrscr(); For {
For printf("%d%d\t",a,b);
for(int
a=0;a<=12;a++) printf("%d }
printf("\n");
x 2= }
%d\n",a,a*2); getch(); getch();
} }

#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr();
int a=0,b;
0x2=0 while(a<=3)
1x2=2 {
2x2=4 b=0;
3x2=6 while(b<=3)
#include<stdio.h> 4x2=8 {
5 x 2 = 10 01 02
While #incl printf("%d%d\t",a,b);
ude<conio. h> 6 x 2 = 12 While b++; 11 12
void main(void) 7 x 2 = 14 } 21 22
{ clrscr(); int 8 x 2 = 16 printf("\n"); 31 32
a=0; 9 x 2 = 18 a++;
while(a<=12) }
10 x 2 = 20 getch();
{
11 x 2 = 22 }
printf("%d x 2 = %d\n",a,a*2);
a++; 12 x 2 = 24
}
getch();
}

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int
a=0,b;
do
{
Do while b=0;
Do while do
#include<stdio.h> {
#i nclude<conio. printf("%d%d\t",a,b);
h>void main(void) b++;
{ }while(b<=3);
clrscr() printf("\n");
; int a++; }while(a<=3);
a=0; do getch();
{
printf("%d x 2 = %d\n",a,a*2); }
a++;
}
while(a<=12);
getch(); 00
} 10
20
30

28
This program of while loops takes continuous input until enter key is pressed.
Program Output
#include<stdio.h>
#include<conio.h>void main(void)

{ clrscr();

Type any sentence


int a=0; Iqra University
printf("Type any sentence\n"); Total Characters typed = 15
while(getche()!='\r')
a++; printf("\nTotal Characters typed = %d",a);
getch();

}
Exercise
Carefully observer the following program and write output with reasons.
Program Output
#include<stdio.h>
#include<conio.h
> void main(void)
{
clrscr();
for(int a=0;a<=12;a++);
printf("%d x 2 = %d\n",a,a*2);
getch(); }

#include<stdio.h>
#include<conio.h
> void main(void)
{
clrscr();
for(int a=0;1 ;a++);
printf("%d x 2 = %d\n",a,a*2);
getch(); }

infinite result
#include<stdio.h>
#include<conio.h
> void main(void)
{ clrscr();
int a=0;
while(0)
{ printf("%d x 2 = %d\n",a,a*2); a++;
} getch();
}

#include<stdio.h>
#include<conio.h
> void main(void)
{ clrscr();
int a=0,b;
while(a<=3)
;
{
b=0;
while(b<=3);
{
printf("%d%d\t",a,b);
b++;
}
printf("\n");
a++;
} getch();
}

Program:
Following program gives the sum of all numbers input by the user using while loop. The program will display the
sum when user enters 0 as input.
#include<conio.h>
#include<stdio.h>
30
Understand the difference between break and continue by executing following programs.
break continue
int main() int main()
{ int { int
i; i;
double number, sum = 0.0; double number, sum = 0.0;

for(i=1; i <= 10; ++i) for(i=1; i <= 10; ++i)


{ {
printf("Enter a n%d: printf("Enter a n%d:
",i); scanf("%lf",&number); ",i); scanf("%lf",&number);

// If user enters negative number, // If user enters negative number,


loop is terminated if(number < loop is terminated if(number <
0.0) 0.0)
{ {
break; continue;
} }
sum += number; // sum = sum + number; sum += number; // sum = sum + number;
} }
printf("Sum = %.2lf",sum); printf("Sum = %.2lf",sum);

return 0;
return 0;
} }

Studying loops with cross combination

do- do-
for while for do- while while do- while
while for while for while while
for( ) while( ) for( ) { do while( ) do
{ { for( d { for( ) { {
while( ) ) o while( }while( do while( )
} } ) while( ) }while(
)
} )
}
Example

The table below shows loops with cross combinations.


Loop Program Output
#include<stdio.h>
#i ncl ude<conio.
h>void main(void)
{ clrscr(); int
a,b=0;
for(a=0;a<=3;a++)
{
b=0;
while(b<=3)
{
For While printf("%d%d\t",a,b);
b++;
}
printf("\n");

} 00 01 02 03
getch(); 10 11 12 13
} 20 21 22 23
#include<stdio.h>

#i ncl ude<conio. h>void 30 31 32 33


main(void)

{ clrscr();
int a=0,b;
while(a<=3)
{
While For for(b=0;b<=3;b++)
{
printf("%d%d\t",a,b);
}
printf("\n");
a++;
}
getch();
}

Assignment

1. Input any number from user and generate its factorial e.g. factorial of 7 is 5040.
#include <stdio.h>

int main() {
int
number;
printf("Enter a number: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
return 0;
}
unsigned long long factorial = 1;
int i;
for (i = 1; i <= number; ++i) {
factorial *= i;
}
printf("Factorial of %d is %llu\n", number, factorial);
return 0;

}
2. Write a program using loops to generate following pattern.

#include <stdio.h>
int main() {
int rows, i, j, k;
printf("Enter the number of rows for the star pyramid: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= rows - i; ++j) {
printf(" ");
}
for (k = 1; k <= 2 * i - 1; ++k) {
printf("*");
}
printf("\n");
}

return 0;
}

3. Write a program using loops to generate following pattern.

1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654320
#include <stdio.h>

int main() {
int rows, i, j;
printf("Enter the number of rows for the pattern: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= rows - i; ++j) {
printf(" ");
}
for (j = 1; j <= i; ++j) {
printf("%d", j);
}
for (j = i - 1; j >= 1; --j) {
printf("%d", j);
}

printf("\n");
}

return 0;

4. Write a program using loops to generate following output.

12 x 2 = 24
11 x 2 = 22
10 x 2 = 20
9 x 2 = 18
34
8 x 2 = 16
7 x 2 = 14
6 x 2 = 12
5 x 2 = 10
4 x 2 = 8
3 x 2 = 6
2 x 2 = 4
1 x 2 = 2
#include <stdio.h>
int main() {
int i;
for (i = 12; i >= 1; --i) {
printf("%d x 2 = %d\n", i, i * 2);
}
return 0;
}

5. The Fibonacci sequence is a series where the next term is the sum of pervious two terms. Write a C
program to generate this sequence.
#include <stdio.h>

int main() {
int n, i, term1 = 0, term2 = 1, nextTerm;

printf("Enter the number of terms in the Fibonacci sequence: ");


scanf("%d", &n);
printf("Fibonacci Sequence: %d, %d, ", term1, term2);
for (i = 3; i <= n; ++i) {
nextTerm = term1 + term2;
printf("%d, ", nextTerm);
term1 = term2;
term2 = nextTerm;
}

return 0;
}
Experiment 7
Objective
Decision making and conditioning using If statements, If-else statements, switch-case.
Theory

If Nested If If-else Else-if Switch-case

if(cond) if(cond) if(cond) if(cond) switch(cond)

{ { { { {

Body If(cond) body body case‟1„:

} { } } body

body else else case‟2„:

} { If(cond) body

} Body { }

} Body
}
Example

This program illustrates simple if and nested if statements with else conditions.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr(); char
ch; int
chr=0,wrd=1;
printf("Type any sentence\n");

while((ch=getche())!='\r') Type any sentence


{ Iqra Univ Khi Sindh Pak
chr++; Total Characters = 19 Total
' ' if(ch==)
{ Words = 5
wrd++; chr--
;
}
}
printf("\nTotal Characters =
%d",chr); printf("\nTotal Words =
%d",wrd); getch();
}

36
#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr(); int cp=0; printf("Enter CP
marks between 1 & 100\n");
scanf("%d",&cp);
if(cp>=0 && cp<=100)
{
if(cp>=75) printf("\nGrade
A");

else if(cp>=50)
printf("\nGrade C");
}
else
printf("\nIncorrect Input");
getch();
}

This program lets the user choose a number between 1 and 99 and guesses it in less than 10 hints.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ clrscr();
float gss,incr;
char ch;
printf("Think of a number Between 1 & 99\n");

printf("Press `g` for grateñn"); Think of a number between 1 and 99


printf("Press `l` for less\n"); Press `g` for greater
printf("Enter for exit\n"); Press `l` for less
Enter for exit
incr=gss=50;
while(incr>1 .0) Is your number greater, less or equal to 50
{
printf("\nIs your number greater, less or equal to Is your number greater, less or equal to 75
%.0f\n",gss); incr/=2; if((ch=getch())=='e') Is your number greater, less or equal to 88
break; You guessed 88
else if(ch=='g')
gss+=incr;
else gss-=incr;
}
printf("You guessed %.0f",gss);
getch();
}

This program prompts the user to type his/her name. If any thing other than Upper/lower case alphabets or a space is
entered for example 1 ,2,@#$% then it is detected and nothing is printed until a correct character is input.
Program Output
#include<stdio.h>
#include<conio.h
> void main(void)
{
clrscr(); char ch;
printf("Name : ");
while((ch=getche())!='\r')
{
if( (ch>=65 && ch<=90) || (ch>=97 && ch<=122) || ch==' '
); else
printf("\b \b");
}
getch();

This is a simple calculator program that adds or subtracts two numbers entered by the user.
Program Output
This is same as the previous one except it take numbers instead of operators to show that switch can also accept numbers.
Program Output
include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
float nm1 =1 .0,nm2=1
.0; int op;
while(!(nm1==0.0 && nm2==0.0))
{
printf("\nType Number Operator Numbeñn");
printf("\nType 1 for addition and 2 for subtraction in
operatoñn"); scanf("%f %d %f",&nm1,&op,&nm2);
switch(op)
{
case 1:
printf(" = %f ",nm1+nm2);
break;
case 2:
printf(" = %f ",nm1-nm2);
break;
default:
printf("\nUnknown
Operatoñn"); }
printf("\n\n");
}
getch();
}#

Assignment

1. Program the following.


• Make the number guessing program with switch case.
#include <stdio.h>
38
#include <stdlib.h>
#include <time.h>

int main() {
int guess, number, attempts = 0;
srand(time(NULL));
number = rand() % 100 + 1; // Generates a random number between 1 and 100

printf("Welcome to the Number Guessing Game!\n");


printf("Try to guess the number between 1 and 100.\n");

do {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;

switch (guess) {

case 0:
printf("Exiting the game. The number was %d.\n", number);
break;
case 1 ... 100:
if (guess < number) {
printf("Too low! Try again.\n");
} else if (guess > number) {
printf("Too high! Try again.\n");
} else {
printf("Congratulations! You guessed the number in %d attempts.\n", attempts);
}
break;
default:
printf("Invalid guess. Please enter a number between 1 and 100.\n");
}

} while (guess != number && guess != 0);

return 0;
}
• Make an alphabet guessing program using if-else.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
char target, guess;
srand(time(NULL));
target = 'a' + rand() % 26;
printf("Welcome to the Alphabet Guessing Game!\n");
printf("Try to guess the letter between 'a' and 'z'.\n");
do {
printf("Enter your guess: ");
scanf(" %c", &guess);
if (guess >= 'a' && guess <= 'z') {
if (guess < target) {
printf("Too low! Try again.\n");
} else if (guess > target) {
printf("Too high! Try again.\n");
} else {
printf("Congratulations! You guessed the letter.\n");
}
} else {
printf("Invalid guess. Please enter a lowercase letter.\n");
}

} while (guess != target);

return 0;

• Complete the simple calculator program for multiplication and division. Also make it using if-else.
#include <stdio.h>

int main() {
double num1, num2;
char operator;

// Input
printf("Enter first number: ");
scanf("%lf", &num1);

printf("Enter an operator (+, -, *, /): ");


scanf(" %c", &operator);

printf("Enter second number: ");


40
scanf("%lf", &num2);
if (operator == '+') {
printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
} else if (operator == '-') {
printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
} else if (operator == '*') {
printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);
} else if (operator == '/') {
// Check for division by zero
if (num2 != 0) {
printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
} else {
printf("Error: Division by zero is undefined.\n");
}
} else {
printf("Invalid operator.\n");
}

return 0;
}

• Make your resume such that in the name field it does not accept anything else than alphabets and space bar.
Look at the scenario below.

Design a marks sheet for a student with 5 subjects includingMath, Physics,


Electronics, Islamiat and Programming Fundamentals.

Take marks as input from user calculate grade for each subject,CGPA and
percentage.

Detect error for out ranged numbers e.g. below 0 or above 100.
#include <stdio.h>

// Function to calculate GPA based on marks


#include <stdio.h>

// Function to calculate GPA based on marks

double calculateGPA(int marks) {

if (marks >= 0 && marks <= 49) {

return 2.0;
} else if (marks >= 50 && marks <= 59) {

return 2.25;

} else if (marks >= 60 && marks <= 69) {

return 2.5;

} else if (marks >= 70 && marks <= 79) {

return 2.75;

} else if (marks >= 80 && marks <= 89) {

return 3.0;

} else if (marks >= 90 && marks <= 95) {

return 3.5;

} else if (marks >= 96 && marks <= 100) {

return 4.0;

} else {

return -1.0;

// Function to get the grade character based on GPA

char getGrade(double gpa) {

if (gpa == 4.0) {

return 'A';

} else if (gpa >= 3.5) {

return 'B';

} else if (gpa >= 3.0) {

return 'C';

} else if (gpa >= 2.75) {

return 'D';

} else {

return 'F';
42
}

int main() {

char name[50];

int marksMath, marksPhysics, marksElectronics, marksIslamiat, marksProgramming;

printf("Enter student's name: ");

scanf(" %[^\n]", name); // Corrected to handle strings with spaces

printf("Enter marks for Math: ");

scanf("%d", &marksMath);

printf("Enter marks for Physics: ");

scanf("%d", &marksPhysics);

printf("Enter marks for Electronics: ");

scanf("%d", &marksElectronics);

printf("Enter marks for Islamiat: ");

scanf("%d", &marksIslamiat);

printf("Enter marks for Programming Fundamentals: ");

scanf("%d", &marksProgramming);

if (marksMath < 0 || marksMath > 100 || marksPhysics < 0 || marksPhysics > 100 ||

marksElectronics < 0 || marksElectronics > 100 || marksIslamiat < 0 || marksIslamiat > 100 ||

marksProgramming < 0 || marksProgramming > 100) {

printf("Error: Marks should be between 0 and 100.\n");


return 1;

double gpaMath = calculateGPA(marksMath);

double gpaPhysics = calculateGPA(marksPhysics);

double gpaElectronics = calculateGPA(marksElectronics);

double gpaIslamiat = calculateGPA(marksIslamiat);

double gpaProgramming = calculateGPA(marksProgramming);

double cgpa = (gpaMath + gpaPhysics + gpaElectronics + gpaIslamiat + gpaProgramming) / 5.0;

double percentage = (marksMath + marksPhysics + marksElectronics + marksIslamiat + marksProgramming) / 5.0;

printf("\nStudent Name: %s\n", name);

printf("Subject\t\tMarks\tGrade\tGPA\n");

printf("Math\t\t%d\t%c\t%.2f\n", marksMath, getGrade(gpaMath), gpaMath);

printf("Physics\t\t%d\t%c\t%.2f\n", marksPhysics, getGrade(gpaPhysics), gpaPhysics);

printf("Electronics\t%d\t%c\t%.2f\n", marksElectronics, getGrade(gpaElectronics), gpaElectronics);

printf("Islamiat\t%d\t%c\t%.2f\n", marksIslamiat, getGrade(gpaIslamiat), gpaIslamiat);

printf("Programming\t%d\t%c\t%.2f\n", marksProgramming, getGrade(gpaProgramming), gpaProgramming);

Marks Grade GPA


0-49 F 2
50-59 C 2.25
60-69 C+ 2.5
70-79 B 2.75
80-89 B+ 3
90-95 A 3.5
96-90 A+ 4

printf("\nCGPA: %.2f\n", cgpa);

printf("Percentage: %.2f%%\n", percentage);

return 0;

}
2. Program the following.
44
• Ask User to select one option from the following.
• Calculate area of Circle [c]
• Calculate area of Rectangle [r]
• Calculate area of Triangle [t]

• If user enters c then ask user to enter radius and calculate area using following formula.

• If user enters r then ask user to enter length & width and calculate area using following formula.

• If user enters t then ask user to enter base & height and area using following formula.

• Display the area.

#include <stdio.h>

// Function to calculate the area of a circle


float calculateCircleArea(float radius) {
return 3.14 * radius * radius;
}

// Function to calculate the area of a rectangle


float calculateRectangleArea(float length, float width)
{ return length * width;
}

// Function to calculate the area of a triangle


float calculateTriangleArea(float base, float height) {
return 0.5 * base * height;
}

int main() {
char
option;
float radius, length, width, base, height, area;

// Display menu options


printf("Select an
option:\n");
printf("[c] Calculate area of Circle\n");
printf("[r] Calculate area of Rectangle\n");
printf("[t] Calculate area of Triangle\n");
printf("Enter your choice: ");
scanf(" %c", &option);

switch (option) {
case 'c':
// Calculate area of Circle
printf("Enter the radius of the cir

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy