0% found this document useful (0 votes)
19 views57 pages

Sahil PF Lab Manul

The document is a lab manual for CS102 - Programming Fundamentals at SMI University, detailing various programming concepts in C language. It includes a table of contents outlining laboratory experiments, objectives, and coding tasks related to Turbo C IDE, C building blocks, and basic programming constructs. Each experiment provides theoretical explanations, coding examples, and expected outputs for students to practice and learn programming fundamentals.

Uploaded by

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

Sahil PF Lab Manul

The document is a lab manual for CS102 - Programming Fundamentals at SMI University, detailing various programming concepts in C language. It includes a table of contents outlining laboratory experiments, objectives, and coding tasks related to Turbo C IDE, C building blocks, and basic programming constructs. Each experiment provides theoretical explanations, coding examples, and expected outputs for students to practice and learn programming fundamentals.

Uploaded by

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

Department of Computer Science

Lab Manual

CS102 – Programming Fundamentals

BS (CS)

Semester: I

Mr. AMEEN KHOWAJA (Course Supervisor)


Mr. ASIF KHAN (Lab Instructor)

Submitted by:
Sahil Kumar
CSC-25S-044

1
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Table of Contents

Lab. No. Description Page No.


1 Introduction of Turbo C IDE and Programming Environment 3

2 C Building Blocks 6

3 Looping constructs in C-Language 9

4 Decision making the if-else and else if structure 12

5 Nested loops (for, while, do while) 16

6 Decision making switch and conditional (Ternary) operator 19

7 Functions in C-Language 22

8 Recursion functions in C 25

9 Arrays in C (single dimensional, Multidimensional) 29

10 C programming string 32

11 Preprocessor Directives 35

12 Pointers in C-Language 28

13 Files in C-language 35

14 Structure in C-language 35

2
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

_________ ____________
Student ID Student Name

Laboratory Experiment 01
Objective of Experiment: Introduction of Turbo C IDE and Programming Environment

Goals: Students will be able to understand the Turbo C IDE and Programming Environment.
.
Required Tools / Equipments:
 PC
 Turbo C (IDE)

Theory:
Integrated Development Environment (IDE):
The Turbo C compiler has its own built-in text editor. The files you create with text editor are
called Source files, and for C they typically are named with the extension .CPP, .CP, or .C.
The C Developing Environment, also called as Programmer’s Platform, is a screen display with
windows and pull-down menus. The program listing, error messages and other information are
displayed in separate windows. The menus may be used to invoke all the operations necessary to
develop the program, including editing, compiling, linking, and debugging and program
execution.

Default Directory
The default directory of Turbo C compiler is c:\tc\bin

3
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Using Menus
If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To select
different menu, move the highlight left or right with cursor (arrow) keys. You can also revoke
the selection by pressing the key combination for the specific menu.

Opening New Window


To type a program, you need to open an Edit Window. For this, open File menu and click
“New”. A window will appear on the screen where the program may be typed.

Writing a Program
When the Edit window is active, the program may be typed. Use the certain key combinations
to perform specific edit functions.

Saving a Program
To save the program, select Save command from the File menu. This function can also be
performed by pressing the [F2] button. A dialog box will appear asking for the path and name
of the file. Provide an appropriate and unique file name. You can save the program after
compiling too but saving it before compilation is more appropriate.

Making an Executable File


The Source file is required to be turned into an Executable file. This is called “Making” of the
.exe file. The steps required to create an executable file are:
1. Create a source file, with a .c extension.
2. Compile the source code into a file with the .obj extension.
3. Link your .obj file with any needed libraries to produce an executable program.

All the above steps can be done by using Run option from the menu bar or using key
combination Ctrl+F9 (By this, linking and compiling is done in one step).

Compiling the Source Code


Although the source code in your file is somewhat cryptic and anyone who doesn’t know C will
struggle to understand what it is for, it is still in what we call human-readable form. But for the
computer to understand this source code, it must be converted to machine-readable form. This is
done by using a compiler. Hence, compiling is the process in which source code is translated into
machine understandable language.
This can be done by selecting Compile option from menu bar or using key combination Alt+F9.

Creating an Executable file with Linker


After your source code is compiled, your object file is produced. This file is often name with
extension .OBJ. This is still not an executable program however. To turn this into an executable
program, you must learn your Linker. C programs are typically created by linking together one
or more OBJ files with one or more libraries. A library is a collection of linkable files that were
supplied with your compiler.

4
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Compiling and Linking in IDE


Compiling and linking can be done in one step. There are two ways to do this: you can select
MAKE EXE from Compile menu, or you can press the [F9] key.

Executing a program
If the program is linked and compiled without errors, the program is executed by selecting Run
from the Run menu or by pressing Ctrl+F9 key combination.

Exiting IDE
An Edit window may be closed in a number of different ways. You can click on the small
square in the upper left corner, you can select Close from the Window menu, or you can press
the [Alt][F3] combination. To exit from the IDE, select Exit from File menu or press [Alt][X]
Combination.

Technical Exits
To minimize the screen of Turbo C editor, press Alt+Enter. If some where the program hangs
up compiler at output or gets busy without passing control to programmer press
Ctrl+Pause/Break.

Student’s tasks:
Answer the following questions:
1. Write the following program in C Editor and execute it. Mention the Errors if any.
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
printf(“Hello World”);
getch();
}

Ans:_ printf(“Hello World”); uses curly quotes (“ ”) instead of standard double quotes ("),
which will cause a compilation error.

Fix: printf("Hello World");

_____________________________________________________________

5
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

2. Make the following changes to the program. What Errors are observed?
1. Write Printf instead of printf .
2. Write void main (void);
3. Erase any one of brace ‘{’ or ‘}’.
4. Erase semicolon ‘;‘ after bracket ’)’ of Hello World.
5. Erase Header Files #include<…> and #include<…>

Ans: 1 Undefined symbol 'Printf'

C is case-sensitive. Printf is not the same as printf. Since Printf is not defined anywhere, the

compiler gives an "undefined symbol" error.

2 Function 'main' must have a body.

Adding a semicolon here tells the compiler that main() is only a declaration, not the actual

function. Since every C program must have a defined main() function, this causes a

compilation error due to the missing function body.

3 Unexpected end of file:

Every opening { must have a matching closing }. Without it, the compiler thinks the block never

ends and reaches EOF unexpectedly.

4 Statement missing ;

Every statement in C must end with a semicolon. Omitting it causes a syntax error.

5 Undefined symbol 'clrscr'

Undefined symbol 'printf'

Undefined symbol 'getch'

Header files provide function declarations. Without including stdio.h, the compiler doesn’t know

what printf is. Similarly, conio.h is needed for clrscr() and getch().

6
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

3. Write a program in c language to print your bio-data on the screen by using printf function.
(Name, Roll no, Semester, Batch, Department, University).

CODE:

OUTPUT:

4. What is wrong in the following program:

7
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

#include<stdio.h>
#include<conio.h>
Void main[void];
(
clrscr();
printf(Welcome to Computer Lab)
getch();
}

Ans:

 Error in line 3

Void should be lowercase: Void → void

main[void]; is invalid syntax.

You’ve used square brackets [] instead of parentheses ().

Ends with ;, which declares a function instead of defining it.

 Error in line 4

Opening parenthesis ( is invalid here.

C expects { to open a function body, not a parenthesis.

 Error in line 5

This line is correct only if you are using Turbo C and have included <conio.h>

 Error in line 6

Missing double quotes around the string.

Missing semicolon ; at the end.

 Error in line 7

This is correct in Turbo C, but again — you must have included <conio.h>.

 Error in line 8

Closing brace is fine — but it's unmatched due to earlier use of ( instead of {.

8
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

LABORATORY EXPERIMENT 01 COMPLETED

_________ __________________ _____________________


Date Lab Instructor Sign. Course Instructor
Sign.

_________ ____________
Student ID Student Name

9
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Laboratory Experiment 02
Objective of Experiment: C Building Blocks

Theory:
In any language there are certain building blocks:
 Constants
 Variables
 Operators
 Methods to get input from user (scanf( ), getch( ) etc.)
 Methods to display output (Format Specifier, Escape Sequences etc.) etc.

Format Specifier
Format Specifier tell the printf statement where to put the text and how to display the text.
The various format specifiers are:
%d => integer
%c => character
%f => float
%e => displays number in scientific notation (float)
%c =>displays a character
%s =>displays a string
%o =>displays an octal number (unsigned)
%x =>displays a hexadecimal number (unsigned)

Variables and Constants


If the value of an item is to be changed in the program then it is a variable. If it will not change
then that item is a constant. The various variable types (also called data type) in C are:
int, float, char, long ,double etc they are also of the type signed or unsigned.

Escape Sequences
Escape Sequence causes the program to escape from the normal interpretation of a string, so that
the next character is recognized as having a special meaning. The back slash “\” character is
called the “Escape Character”. The escape sequence includes the following:

\n => new line


\t => horizontal tab
\b => back space
\r => carriage return
\’ =>single quote
\” => double quotations
\\ => back slash
\v =>vertical tab
\a =>alert

10
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

\? =>Question mark
\0 =>Null
\f =>form feed, page eject, page or section separator (move active position to the
initial position of next logical page)
\xhh =>hexa decimal escape sequence
\ddd =>octal escape sequence

Taking Input from the User


The input from the user can be taken by the following techniques: scanf( ), getch(), getche( ),
getchar( ) etc. getchar() is a standard function that gets a character from the stdin.
e.g: char c;
printf(“Enter character”);
c= getchar();

getch() is a nonstandard function that gets a character from keyboard, does not echo to screen.
getche() is a nonstandard function that gets a character from the keyboard, echoes to screen.

Use getchar() if you want it to work on all compilers. Use getch() or getche() on a system that
supports it when you want keyboard input without pressing [Enter].

Operators
There are various types of operators that may be placed in three categories:
Basic: + - * / %
Assignment: = += -= *= /= %=
Increment / decrement operators ++, --
Relational: < > <= >= == !=
Logical: && , || , !

11
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Student’s tasks:
1. Write a following program and observe result:

void main (void)


{
char ch='A',str[]="My SMIU";
int num= 2;
float fnum= 12.47;
clrscr();
printf("character= %c\n",ch);
printf("string= %s\n", str);
printf("integer= %d\n", num);
printf("float= %10.6f\n", fnum);
getch();}

CODE:

OUTPUT:

12
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

2.Write a program which take input Name, Age, Height, Gender and print them by using
Escape Sequences and Format Specifiers.

CODE:

OUTPUT:

3. Write a following program and observe the result:

13
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

#include<math.h>
#define pi 3.1415927
void main (void)
{
float altitude,base,radius,t,s;
clrscr ();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("\n\n\t\t Enter the value for Altitude of a Triangle. ");
scanf("%f", &altitude);
printf("\n\n\t\t Enter the value for Base of a Triangle. ");
scanf("%f", &base);
printf("\n\n\t\t Enter the value for Radius of a Sphere. ");
scanf("%f", &radius);
t=(1.0/2.0)*(altitude*base);
s=(4.0/3.0)*pi*pow(radius,3);
if(t<s)
{
printf("\n\n\t\t Area of Triangle = %.2f",t);
printf("\n\n\t\t Volume of Sphere = %.2f",s);
}
else
{
printf("\n\n\t\t Volume of Sphere = %.2f",s);
printf("\n\n\t\t Area of Triangle = %.2f",t);
}
getch ();
}
OUTPUT:

14
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

4.Write C program to perform basic arithmetic operations: addition, subtraction, multiplication


and division of two numbers. Numbers should be integers and will be entered by the user.

ANS:
#include <stdio.h>
#include <conio.h>

void main() {
int num1, num2;
int sum, difference, multiplication;
float division;
clrscr();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("Enter 1st integer: ");
scanf("%d", &num1);
printf("Enter 2nd integer: ");
scanf("%d", &num2);

sum = num1 + num2;


difference = num1 - num2;
multiplication = num1 * num2;
division = (float) num1 / num2;

printf("Addition = %d\n", sum);


printf("Subtraction = %d\n", difference);
printf("Multiplication = %d\n", multiplication);
printf("Division = %f\n", division);
getch();
}

OUTPUT:

5. What will be the output if count=5,

15
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

printf(“%d”,++count);
printf(“%d”,count++);
printf(“Value of count is= %d”,count);

ANS:

1++count is a pre-increment.

 It increments count first (so count becomes 6), then prints 6.

2 count++ is a post-increment.

 It prints the current value of count (which is 6), then increments count to 7.

3 Finally, it prints count, which is now 7.

LABORATORY EXPERIMENT 02 COMPLETED

_____ __________________ _____________________


Date Lab Instructor Sign. Course Instructor
Sign

_________ ____________
Student ID Student Name

16
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Laboratory Experiment 03

Objective of Experiment: Looping constructs in C-Language

Theory:
There may be a situation, when you need to execute a block of code several numbers of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:

 You want to execute some code/s 100 times.


 You want to execute some code/s certain number of times depending upon input
from user.
These types of task can be solved in programming using loops.

There are 3 types of loops in C programming:

 For Loop
 While Loop
 Do-While Loop

For Loop
For example: Write a program to find the sum of first n natural numbers where n is
entered by user. Note: 1,2,3... are called natural numbers.
The syntax of for loop
for(initialize expression; test condition expression; increment expression)
{
set of statements
}

17
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Nested For loop


for(initialize expression; test condition expression; increment expression)
{
for(initialize expression; test condition expression; increment expression)
{
set of statements
}

While loop
The while loop checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed, that is, code/s inside the braces { } are
executed. Then again the test expression is checked whether test expression is true or
not. This process continues until the test expression becomes false.

18
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Syntax of while loop

while (test expression)


{
statement/s to be executed.
}

Nested while loop


while (test expression)
{
while (test expression)
{
statement/s to be executed.
}

}
Do while loop
At first codes inside body of do is executed. Then, the test expression is checked. If it
is true, code/s inside body of do are executed again and the process continues until test
expression becomes false(zero).

Syntax of do while loop

do
{
some code/s;
}
while (test expression);

Nested do while loop


do
{
do
{
some code/s;
}

19
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

while (test expression);


}
while (test expression);

Student’s tasks:
.
1. Write a following program to add n number of elements.
void main(void)
{
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
getch();
}

ANS:

#include<stdio.h>
#include<conio.h>
void main(void) {
int n,count,sum=0;
clrscr();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("Enter the value of : \n");
scanf("%d",&n);
for(count=1;count<=n;count++)
{
sum+=count;
}
printf("sum=%d",sum);
getch();}

20
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

OUTPUT:
2. Program generates Multiplication Table of number between 2 to 20.
void main (void)
{
int i,n,j=0;
clrscr ();
printf("\n\t\tEnter Table No. ");
scanf("%d",&n);
if(n>=2 && n<=20)
for(i=1;i<=12;i++)
{
j=n*i;
printf("\n\t\t%d * %d = %d",n,i,j);
}
else
printf("\nError!!! Enter number from 2 to 20");
getch ();
}

ANS:
#include<stdio.h>
#include<conio.h>
void main (void)
{
int i,n,j=0;
clrscr ();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("\n\t\tEnter Table No. ");
scanf("%d",&n);
if(n>=2 && n<=20)
for(i=1;i<=12;i++)
{
j=n*i;
printf("\n\t\t%d * %d = %d",n,i,j);
}
else
printf("\nError!!! Enter number from 2 to 20");

21
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

getch ();
}

OUTPUT:

3. Program to find factorial of a given number.


void main(void)
{
clrscr();
double f;
int num;
// computes the product n*(n-1)*(n-2)*(n-3)*...*2*1
while(num!=0)
{
printf("\n\n\n\t\tEnter the number to find its factorial: ");
scanf("%d",&num);
f=1;
while(num>1)
{
f=f*num;
num--;
}
printf("\t\tThe factorial is %lf",f); }}

22
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

OUTPUT:

4. During execution of following program, how many lines of asterisks are displayed?
for(i=0;i<3;++i)
for(j=0;j<4;++j)
printf("******\n");

ANS:

 Outer loop (i loop): runs from i = 0 to i < 3 → 3 iterations


 Inner loop (j loop): runs from j = 0 to j < 4 → 4 iterations for each i

So, total executions of printf("******\n") = 3 (outer) × 4 (inner) = 12 times

Final Answer:

12 lines of asterisks (******) are displayed.

5. Write a program to print sum of even numbers from 1 to 100.

ANS:
#include <stdio.h>
#include <conio.h>

void main() {
int i, sum = 0;

clrscr();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
for(i = 2; i <= 100; i += 2) {
sum += i;
}

printf("Sum of even numbers from 1 to 100 is: %d", sum);

23
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

getch();}

OUTPUT:

6. Write a program to print square of all the numbers from 1 to 20.


ANS:
#include <stdio.h>
#include <conio.h>
void main() {
int i;
clrscr();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("Number\tSquare\n");
for(i = 1; i <= 20; i++) {
printf("%d\t%d\n", i, i * i);
}
getch(); }

OUTPUT:

24
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

7.Write a program of nested loop that cause following output to be displayed.


*****
****
***
**
*
**
***
****
*****

ANS:
#include <stdio.h>
#include <conio.h>

void main() {
int i, j;
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
clrscr();
for(i = 5; i >= 1; i--) {
for(j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
for(i = 2; i <= 5; i++) {
for(j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}

getch();
}

25
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

OUTPUT:

LABORATORY EXPERIMENT 03 COMPLETED

_________ __________________ _____________________


Date Lab Instructor Sign. Course Instructor Sign.

_________ ____________
Student ID Student Name

26
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Laboratory Experiment 04
Objective: Decision making structures: If and If-else

Theory:
The if , if...else and nested if...else statement are used to make one-time decisions in C Programming,
that is, to execute some code/s and ignore some code/s depending upon the test condition. Without
decision making, the program runs in similar way every time. Decision making is an important
feature of every programming language using C programming. Before you learn decision making,
you should have basic understanding of relational operators.
 If Statement
 If…Else Statement
 Switch Statement

If Statement
The if statement checks whether the test condition is true or not. If the test condition is true, it
executes the code/s inside the body of if statement. But it the test condition is false, it skips the
code/s inside the body of if statement.
Syntax of If statement
If(condition)
Statement;
Operation of If statement

27
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Working of if Statement

The if keyword is followed by test condition inside parenthesis ( ). If the test condition is true, the
codes inside curly bracket is executed but if test condition is false, the codes inside curly bracket { }
is skipped and control of program goes just below the body of if as shown in figure above.

The if-else statement


Often your program will want to take one branch if your condition is true, another if it is false. If
only one statement is to be followed by the if or else condition then there is no need of
parenthesis. The keyword else is used to perform this functionality.

Syntax of If –Else statement

if (condition)
statement 1; //Executes if Condition is true
else
statement 2; //Executes if condition is false

Operation of If-Else Structure

28
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

29
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Student’s tasks:
1. Write a following program which guesses number user thinking of.

void main(void)
{
float guess,incr;
char ch;
printf("Think of a number between 1 and 99,and\n");
printf("I'will guess what it is. Type 'e' for equals,\n");
printf("'g' for greater than, and 'l' for less than.\n");
incr=guess=50; /* two assignments at once */
while(incr>1.0) /* while not close enough */
{
printf("\nIs your number greater or less than %.0f?\n",guess);
incr=incr/2;
if((ch=getche())=='e') /* if guess it already */
break; /* escape from loop */
else if(ch=='g') /* if guess too low */
guess=guess+incr; /* try higher */
else /* if guess too high */
guess=guess-incr; /* try lower */
}
printf("\nThe number is %.0f. Am I not clever?",guess);
getch();
}

ANS:
#include<stdio.h>
#include<conio.h>
void main(void)
{
float guess,incr;
char ch;
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("Think of a number between 1 and 99,and\n");
printf("I'will guess what it is. Type 'e' for equals,\n");
printf("'g' for greater than, and 'l' for less than.\n");
incr=guess=50;
while(incr>1.0)
{
printf("\nIs your number greater or less than %.0f?\n",guess);
incr=incr/2;
if((ch=getche())=='e')
break;
else if(ch=='g')
guess=guess+incr;
30
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

else
guess=guess-incr;
}
printf("\nThe number is %.0f. Am I not clever?",guess);
getch();
}

31
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

2.What is the output of the following program?

if(temp<80)
{
if(temp>60)
printf(“nice day”); }
else
printf(“sure it is hot”);

ANS:

#include <stdio.h>
#include <conio.h>

void main() {
int temp;
clrscr();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);
printf("Enter the temperature: ");
scanf("%d", &temp);
if(temp < 80) {
if(temp > 60)
printf("Nice day");
} else {
printf("Sure it is hot");
}
getch();}

OUTPUT:

32
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

3.What is the output of the following program?

char x,y;
clrscr();
scanf(“%c”,&x);
scanf(“%c”,&y);
if(x==’n’ && y==’o’)
printf(“you type no”);

ANS:

#include <stdio.h>
#include <conio.h>

void main() {
char x, y;

clrscr();
printf (“Name:Sahil kumar\nRoll No:CSC-25S-044”);

printf("Enter two characters: ");


scanf("%c", &x);
scanf(" %c", &y); // notice the space before %c

if(x == 'n' && y == 'o')


printf("you type no");

getch();
}

OUTPUT:

33
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

4.Write a program which takes a character input and checks whether it is vowel or
consonant?

ANS:

#include <stdio.h>

#include <conio.h>

void main() {

char ch;

clrscr();

printf(“Name:Sahil kumar\nRoll No:CSC-25s_044”);

printf("Enter a character: ");

scanf("%c", &ch);

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||

ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

printf("It is a vowel.");

} else{

printf("It is a consonant.");

getch();

OUTPUT:

34
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

5.Write a program that inputs an integer and determine if it is even or odd.?


ANS:
#include <stdio.h>
#include <conio.h>
void main() {
int num;
clrscr();
printf(“Name:Sahil kumar\nRoll N:CSC-25S-044\n”);
printf("Enter an integer: ");
scanf("%d", &num);
if(num % 2 == 0)
printf("The number is even.");
else
printf("The number is odd.");

getch();
}

OUTPUT:

LABORATORY EXPERIMENT 04 COMPLETED

_________ __________________ _____________________


Date Lab Instructor Sign. Course Instructor Sign.

_________ ____________
Student ID Student Name

35
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Laboratory Experiment 05
Objective:
Decision making structure: switch statement and conditional (Ternary) operator

Theory:
Normally, your program flows along line by line in the order in which it appears in your source
code. But, it is sometimes required to execute a particular portion of code only if certain
condition is true; or false i.e. you have to make decision in your program. There are three major
decision making structures. The ‘if’ statement, the if-else statement, and the switch statement.
Another less commonly used structure is the conditional operator.

The switch Statement


Unlike if , which evaluates one value, switch statements allow you to branch on any of a number
of different values. There must be break at the end of the statements of each case otherwise all
the preceding cases will be executed including the default condition.

The general form of the switch statement is:

switch(expression)
{
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;

/* you can have any number of case statements */


default :
statement(s);
}

Conditional Operator
The conditional operator ( ?: ) is C’s only ternary operator; that is, it is the only operator to
take three terms.
The conditional operator takes three expressions and returns a value:
(expression1) ? (expression2) : (expression3)
It replaces the following statements of if else structure
if(a>b)
c=a;
else
c=b;
can be replaced by

36
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

c=(a>b)?a:b

This line is read as “If expression1 is True, return the value of expression2; otherwise, return the
value of expression3”. Typically, this value would be assigned to a variable.

Student’s tasks:

1. ‘Write a following program and observe the output.


void main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
getch();
}

OUTPUT:

37
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

2. What is the output of the following program?


color =’R’;
switch(color)
{
case ‘R’:
printf(“Red\n”);
case ‘B’:
printf(“Blue\n”);
case ‘Y’:
printf(“Yellow\n”);
}

OUTPUT:

3. What is the output of the following program?


float i=1.5;
switch(i)
{
case 1:
printf(“1”);
case 2:
printf(“2”);
case 3:
printf(“0”);
}

ANS:
This question find an error(switch selection must be of integral type).

38
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

4.What is the output of the following program?


main()
{
int k=1;
printf(“%d==1 is “”%s”,k,k==1?”TRUE”:FALSE”);
}

ANS:
#include<stdio.h>
#include<conio.h>
void main()
{
int k=1;
clrscr();
printf(“Name:Sahil kumar\nRoll No:CSC_25S-044\n”);
printf(“%d==1 is “”%s”,k,k==1?”TRUE”:”FALSE”);
getch();
}

OUTPUT:

5.Write a program that asks user an arithmetic operator ('+','-','*', '/',%) and two
operands and perform the corresponding calculation on the operands.

ANS:

#include <stdio.h>

#include <conio.h>

void main() {

char op;

int a, b, result;

clrscr();

39
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

printf(“Name :Sahil kumar\n Roll No:CSC-25S-044\n”);

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

scanf("%c", &op);

printf("Enter two integers: ");

scanf("%d %d", &a, &b);

switch(op) {

case '+':

result = a + b;

printf("Result = %d", result);

break;

case '-':

result = a - b;

printf("Result = %d", result);

break;

case '*':

result = a * b;

printf("Result = %d", result);

break;

case '/':

if(b != 0)

printf("Result = %d", a / b);

else

printf("Error: Division by zero");

break;

case '%':
40
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

if(b != 0)

printf("Result = %d", a % b);

else

printf("Error: Modulo by zero");

break;

default:

printf("Invalid operator");

getch(); }

OUTPUT:

6.Write a program which takes a text input and count total number of vowels, consonants
and other special characters and print the result?

ANS:

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

void main() {
char text[100];
int i = 0, vowels = 0, consonants = 0, special = 0;

41
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

clrscr();

printf("Enter a line of text: ");


fflush(stdin);

while(text[i] != '\0') {
char ch = tolower(text[i]);

if(ch >= 'a' && ch <= 'z') {


if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
} else if(ch != ' ') {
special++;
}

i++;
}

printf("Vowels: %d\n", vowels);


printf("Consonants: %d\n", consonants);
printf("Special characters: %d\n", special);
getch();}

OUTPUT:

7. Write a program which takes 10 integers as input and prints the largest one.

ANS:

#include <stdio.h>
#include <conio.h>
void main() {
int numbers[10], i, max;
clrscr();
printf(“Name:Sahil kumar\nRoll No:CSC-25S-044\n”);
printf("Enter 10 integers:\n");
for(i = 0; i < 10; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &numbers[i]);
42
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

}
max = numbers[0];
for(i = 1; i < 10; i++) {
if(numbers[i] > max) {
max = numbers[i];}}
printf("The largest number is: %d", max)
getch(); // Wait for a key press}

OUTPUT:

LABORATORY EXPERIMENT 05 COMPLETED

_________ __________________ _____________________


Date Lab Instructor Sign. Course Instructor Sign.

_________ ________________
Student ID Student Name

43
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Laboratory Experiment 06
Objective of Experiment:
Decision making switch and conditional (Ternary) operator

Goals: After completing this lab, the students should be able to understand the concept of
switch and conditional (Ternary) operator.

Required Tools / Equipment’s:

 PC
 Turbo C

Theory:

Normally, your program flows along line by line in the order in which it appears in your source
code. But, it is sometimes required to execute a particular portion of code only if certain
condition is true; or false i.e. you have to make decision in your program. There are three major
decision making structures. The ‘if’ statement, the if-else statement, and the switch statement.
Another less commonly used structure is the conditional operator.

The switch Statement


Unlike if , which evaluates one value, switch statements allow you to branch on any of a
number of different values. There must be break at the end of the statements of each case
otherwise all the preceding cases will be executed including the default condition.

The general form of the switch statement is:

switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

44
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

#include <stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" ); }
printf("Your grade is %c\n", grade );
return 0; }

Conditional Operator
The conditional operator ( ?: ) is C’s only ternary operator; that is, it is the only operator to
take three terms.
The conditional operator takes three expressions and returns a value:
(expression1) ? (expression2) : (expression3)
It replaces the following statements of if else structure
If(a>b)
c=a;
else
c=b;
can be replaced by
c=(a>b)?:a:b

45
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Student’s task:

Answer the following questions:


1. Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands
and perform the corresponding calculation on the operands.?

ANS:

#include <stdio.h>

#include <conio.h>

void main() {

char operator;

float num1, num2, result;

clrscr();

printf(“Name:Sahil kumar\nRoll No:CSC-25S-044\n”);

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

scanf(" %c", &operator);

printf("Enter first number: ");

scanf("%f", &num1);

printf("Enter second number: ");

scanf("%f", &num2);

switch(operator) {

case '+':

result = num1 + num2;

printf("Result: %.2f", result);

break;

case '-':

result = num1 - num2;

46
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

printf("Result: %.2f", result);

break;

case '*':

result = num1 * num2;

printf("Result: %.2f", result);

break;

case '/':

if(num2 != 0)

result = num1 / num2;

else {

printf("Error: Division by zero");

getch();

return;

printf("Result: %.2f", result);

break;

default:

printf("Invalid operator");

getch();

OUTPUT:

47
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

2. .Write a program which takes a text input counts total number of vowels, consonants and other
special characters and prints the result?

Ans:

#include <stdio.h>

#include <conio.h>

void main() {

char text[100];

int i = 0, vowels = 0, consonants = 0, special = 0;

char ch;

clrscr();

printf("Enter a line of text (max 99 characters):\n");

gets(text);

while (text[i] != '\0') {

ch = text[i];

if (ch >= 'A' && ch <= 'Z') {

ch = ch + 32;

if (ch >= 'a' && ch <= 'z') {

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

vowels++;

} else {

consonants++;

} else {

48
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

special++;

i++;

printf("\nVowels: %d", vowels);

printf("\nConsonants: %d", consonants);

printf("\nSpecial Characters: %d", special);

getch();

OUTPUT:

3. Write a program which takes 10 integers as input and prints the largest one.?
Ans:

#include <stdio.h>
#include <conio.h>

void main() {
int numbers[10], i, largest;

clrscr();
printf(“Sahil kumar\nRoll No:CSC-25S-044”);
printf("Enter 10 integers:\n");
for (i = 0; i < 10; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &numbers[i]);
}
largest = numbers[0];

49
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

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


if (numbers[i] > largest) {
largest = numbers[i];
}
}
printf("\nThe largest number is: %d", largest);
getch();
}

OUTPUT:

LABORATORY EXPERIMENT 06 COMPLETED

_________ __________________ _____________________


Date Lab Instructor Sign. Course Instructor Sign.

___________ ___________
Student ID Student Name

50
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

Laboratory Experiment 07
Objective of Experiment:
To understand the concepts of function.

Goals: After completing this lab, the students should be able to understand the concept of
function.

Required Tools / Equipment’s:

 PC
 Turbo C(IDE)

Theory:

The function is a good mechanism to encapsulate code used repeatedly in a program so that it
can be called from other parts of the code. A function does not use a keyword called function but
instead the programmer has to define function prototype before the main function and then
define the function again later.
A function has the following format:

type function_name (optional parameter list )


{
function code ;
return value;
}

Return data type of function is in general the types of C++ variable types including int, double,
char etc.
The function does some processing and the calculated value is returned using the return value.

In the main function or the other functions calling this function_name, the value returned is used
like the instruction:
calling_value = function_name (parameters);

A function does not need to always return a value.


A function not returning a value can omit the return statement and the function type is void in
this case.
Function prototype has the following format: type function_name (list of variable types);

Examples are:

Example 1:

51
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

int compute_sum (int);

Example 2:
void tryout ();

Function prototypes differ from the function definitions in two places: there is no code (no {}
with code in between) and the variable names do not follow the types. A function prototype can
return nothing, in which case void is the type returned; also it may have no parameters at all like
example 2 above. The function prototype is declared before the main function with the function
calls inside the main function or the other functions calling this function.
The function definitions are put after the main function.

C Standard Library : is a collection of functions, which are written in the core language and
part of the C ISO Standard itself to provides several generic functions that utilize and
manipulate these containers, function objects, generic strings and streams (including interactive
and file I/O), support for some language features, and everyday functions for tasks such as
finding the square root of a number. Using sqrt in <cmath> header file.

Student’s task:

Answer the following questions:


1. Write a function called Sum_even which takes as input two integers N and M entered by the
user from keyboard , and returns to the main function the summation of even numbers from N to
M. (note: N and M included if were even numbers) .?

Ans:

#include <stdio.h>

#include <conio.h>

int Sum_even(int N, int M);

void main() {

int N, M, result;

clrscr();

printf(“Name:Sahil kumar\nRoll No:CSC-25S-044”);

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

scanf("%d", &N);

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

52
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

scanf("%d", &M);

result = Sum_even(N, M);

printf("\nSum of even numbers from %d to %d is: %d", N, M, result);

getch();

int Sum_even(int N, int M) {

int sum = 0, i;

for (i = N; i <= M; i++) {

if (i % 2 == 0) {

sum += i;

getch();

Output:

53
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

2. Write a function called Is_Capital that has one parameter and receives a character and returns
true if the character received is a capital letter, and false otherwise. Then write a main function
that calls the Is_Capital function to test its correctness.(you may solve it without using if-else
statement).?

Ans:

#include <stdio.h>

#include <conio.h>

int Is_Capital(char ch);

void main() {

char ch;

int result;

clrscr();

printf("Enter a character: ");

scanf(" %c", &ch);

result = Is_Capital(ch);

if (result)

printf("The character '%c' is a capital letter.", ch);

else

printf("The character '%c' is NOT a capital letter.", ch);

getch(); }

int Is_Capital(char ch) {

return (ch >= 'A' && ch <= 'Z');}

OUTPUT:
54
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

4. Write a C function to receive an integer of 3 digits then calculates and returns the sum of
the MSD and the LSD. For example if your function received 345 it should return 8. ?

Ans:

#include <stdio.h>

#include <conio.h>

int Sum_MSD_LSD(int num) {

int msd, lsd;

lsd = num % 10;

msd = num / 100;

return msd + lsd;}

void main() {

int number, result;

clrscr();

printf("Enter a 3-digit number: ");

scanf("%d", &number);

if (number >= 100 && number <= 999) {

result = Sum_MSD_LSD(number);

printf("The sum of MSD and LSD is: %d", result);

} else {

printf("Invalid input. Please enter a 3-digit number.");}

getch(); }

55
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

OUTPUT:

LABORATORY EXPERIMENT 07 COMPLETED

_________ __________________ _____________________


Date Lab Instructor Sign. Course Instructor Sign.

_________ ____________
Student ID Student Name

56
SMI UNIVERSITY PROGRAMMING FUNDAMENTAL LAB Course Supervisor: AMEEN KHOWAJA

57

You might also like