0% found this document useful (0 votes)
105 views62 pages

CP Lab Exp 1 To 12

This document contains a list of experiments for learning C programming. It includes 12 topics with multiple programs under each topic. The topics cover basic input/output, data types, conditional statements, loops, arrays, strings, functions, pointers, structures, file handling and command line arguments. It also lists some dos and don'ts for students in the lab.

Uploaded by

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

CP Lab Exp 1 To 12

This document contains a list of experiments for learning C programming. It includes 12 topics with multiple programs under each topic. The topics cover basic input/output, data types, conditional statements, loops, arrays, strings, functions, pointers, structures, file handling and command line arguments. It also lists some dos and don'ts for students in the lab.

Uploaded by

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

1

List of Experiment
Exp. Name of experiment
no
1 Simple Input output program.

1.1 WAP to print hello message


1.2 WAP to print value of integer.
1.3 WAP to print addition of two numbers
1.4 WAP to print area of rectangle.

2 Data type, variables & conditional statements (if, if-else,ladder-if)

2.1 W
AP
to
cre
ate
a
file
and
writ
e
dat
a in
it.
2.2 WAP to write any sentence on file.
2.3 WAP to read a line from a file and display it.
2.4 WAP to print size of a file
WA
P to
calc
ulat
e
sim
ple
inte
rest.
WA
P to
swa
p
two
nu
mbe
rs
wit
hou
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 1
2

t
usin
g
thir
d
vari
able
.
WA
P to
che
ck
whe
ther
a
give
n
nu
mbe
r is
eve
n or
odd.
WA
P to
calc
ulat
e
perc
enta
ge
and
defi
nes
its
gra
des
usin
g if
else
if
ladd
er
stat
eme
nt.

3 Nested if-else & switch statements.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 2
3

3.1 WAP to print largest of three numbers


3.2 WAP to implement a simple calculator using switch.

4 Iterative Statements(while & do-while)

4.1 WAP to print natural numbers using while loop.


4.2 WAP to print odd numbers using do-while loop.
4.3 WAP to print sum of the digits of a number.

5 For loop & nested for loop

5.1 WAP to print factorial of a number using for loop.


5.2 WAP to print pyramid pattern.

6 Array and string operations

6.1 WAP to add elements of one dimensional array.


6.2 WAP to print largest number of an array.
6.3 WAP to print addition/multiplication of two dimensional
arrays.
6.4 WAP to print length of a string.
6.5 WAP to check whether a given string is palindrome or not.

7 Sorting & searching


7.1 WAP to search a particular number in array & print location.
7.2 WAP to sort an array in ascending order.

8 Functions & recursion


8.1 WAP to print square of a number using user defined functions.
8.2 WAP to check whether a given number is Armstrong or not
using function.
8.3 WAP to print Fibonacci series using recursion.
8.4 WAP to swap two numbers using call by value & call by
reference method.
9 Structure & Union
9.1 WAP to print details of a student using structure.
9.2 WAP to print details of 10 books using structure.
9.3 WAP to implement union.

10 Pointers
10.1 WAP to print many values of variable using pointers.
10.2 WAP to perform arithmetic operations using pointers
10.3 WAP to print addition of array elements using pointers.

11 File handling functions


DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 3
4

11.1 WAP to write a some of the character (without taking input from
the keyboard) and reading, printing , written characters.
11.2 WAP to write a string to a file & print.
11.3 WAP to implement fprintf() & fscanf().

12 Command line arguments


12.1 WAP to implement simple program of command line.

DO’S AND DONT’S

DO’S

1. Student should get the record of previous experiment checked before starting
the new experiment.
2. Read the manual carefully before starting the experiment.
3. Before starting the experiment, get circuit diagram checked by the teacher.
4. Before switching on the power supply, get the circuit connections checked.
5. Get your readings checked by the teacher.
6. Apparatus must be handled carefully.
7. Maintain strict discipline.
8. Keep your mobile phone switched off or in vibration mode.
9. Students should get the experiment allotted for next turn, before leaving the lab.

DONT’S

1. Do not touch or attempt to touch the mains power supply Wire with bare
hands.
2. Do not overcrowd the tables.
3. Do not tamper with equipments.
4. Do not leave the without permission from the teacher.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 4
5

EXPERIMENT NO. 1

Object:- To learn about the C Library, Preprocessor directive, Input-output


statement.

Introduction:- Before a C program is compiled in a compiler, source code is processed


by a program called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.

1.1 Program to Display "Hello, World!"

#include <stdio.h>
int main()
{
// printf() displays the string inside quotation
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 5
6

printf("Hello, World!");
return 0;
}

Output
Hello, World!

1.2 Program to Print an Integer

#include <stdio.h>
int main()
{
int number;

// printf() dislpays the formatted output


printf("Enter an integer: ");

// scanf() reads the formatted input and stores them


scanf("%d", &number);

// printf() displays the formatted output


printf("You entered: %d", number);
return 0;
}

Output
Enter a integer: 25
You entered: 25

1.3 Program to Add Two Integers

#include <stdio.h>
int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;

printf("Enter two integers: ");

// Two integers entered by user is stored using scanf() function


scanf("%d %d", &firstNumber, &secondNumber);

// sum of two numbers in stored in variable sumOfTwoNumbers


sumOfTwoNumbers = firstNumber + secondNumber;

// Displays sum
printf("%d + %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 6
7

return 0;
}

Output
Enter two integers: 12
11
12 + 11 = 23

1.4 Program to calculate area of rectangle

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

int main() {
int length, breadth, area;

printf("\nEnter the Length of Rectangle : ");


scanf("%d", &length);

printf("\nEnter the Breadth of Rectangle : ");


scanf("%d", &breadth);

area = length * breadth;


printf("\nArea of Rectangle : %d", area);

return (0);
}

Output:
Enter the Length of Rectangle : 5
Enter the Breadth of Rectangle : 4
Area of Rectangle : 2

Experiment no. -1 Viva Voce Question

1.Write down short note on c language. And also describe its features.

Ans: C is a high-level and general-purpose programming developed by Dennis


Ritchie at Bell Laboratories in USA.
C programming language features were derived from an earlier language called “B”
(Basic Combined Programming Language – BCPL).

FEATURES OF C PROGRAMMING LANGUAGE:


C language is one of the powerful language. Below are some of the features of C
language.
 Reliability
 Portability
 Flexibility
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 7
8

 Interactivity
 Modularity
 Efficiency and Effectiveness

2. Define all the c libray function.


Ans: The C Standard Library is a set of C built-in functions, constants and header
files . All C standard library functions are declared in many header files which are
saved as file_name.h. When we include header files in our C program using
“#include<filename.h>” command, all C code of the header files are included in C
program. Then, this C program is compiled by compiler and executed.
like <stdio.h>,<conio.h>, <string.h>, <stdlib.h>, <math.h>, etc.

3. What is preprocessor directive in c language?


Ans: The preprocessor will process directives that are inserted into the C source code.
These directives allow additional actions to be taken on the C source code before it is
compiled into object code.

4. Describe input and output statement.


Ans: In C Language input and output function are available as C compiler function or
C library provided with each C compiler implementation. These all functions are
collectively known as Standard I/O Library function.
Some of the input and output functions are as follows:
i)printf
This function is used for displaying the output on the screen i.e the data is moved
from the computer memory to the output device.
ii)scanf
scanf is used when we enter data by using an input device.

5.write down the function of heaser files stdio.h and conio.h?

Ans: Conio.h : it is a C header file used mostly by MS-DOS compilers to provide


console input/output..
stdio.h : it is a library that allows interaction of the program with the standard input
output i.e Keyboard and monitor.

EXPERIMENT NO. 2

Object: Programs to learn data type, variables, If-else statement.

Theory:-
If-else statement: The if-else statement is a two way branch: it means do one thing or
the other. When it is executed, the condition is evaluated and if it has the value `true'
(i.e. not zero) then statement1 is executed. If the condition is `false' (or zero) then
statement2 is executed. The if-else construction often saves an unnecessary test from
having to be made.
if (condition)
{
statements
}
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 8
9

else
{
statements
}

2.1 WAP to calculate simple Interest.

#include<stdio.h>

int main()
{
int amount, rate, time, si;
printf("\nEnter Principal Amount : ");
scanf("%d", &amount);
printf("\nEnter Rate of Interest : ");
scanf("%d", &rate);

printf("\nEnter Period of Time : ");


scanf("%d", &time);

si = (amount * rate * time) / 100;


printf("\nSimple Interest : %d", si);

return(0);
}
Output :
Enter Principal Amount : 500
Enter Rate of interest : 5
Enter Period of Time : 2
Simple Interest : 50

2.2 WAP to Swap 2 numbers using third variable.

Swapping: This technique in C programming, mean the ability to either:

 Swap two values or


 Swap two references.

In the first instance, taking a variable that contains an item of data, and swapping it
with another variable containing the same type. The actual values are sapped, so that
variable one contains the value of variable two, and variable two contains the value of
variable one.
In the second instance, Reference swapping performs the same function, but it does
not actually swap the value, but only a pointer to that value in memory.

Source Code:

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 9
10

#include <stdio.h>
main()
{
int a,b,temp;
printf("Before Swapping variable a :");
scanf("%d",&a);
printf("Before Swapping variable b :");
scanf("%d",&b);
temp=a;
a=b;
b=temp;
printf("After Swapping variable a=%d",a);
printf("After Swapping variable b=%d",b);
}

Output:
Before Swapping variable a: 3
Before Swapping variable b: 5
After Swapping variable a=5
After Swapping variable b=3

Without using third variable-

#include <stdio.h>
main()
{
int a,b,temp;
printf("Before Swapping variable a :");
scanf("%d",&a);
printf("Before Swapping variable b :");
scanf("%d",&b);
a=a+b;
b=a-b;
a=a-b;
printf("After Swapping variable a=%d",a);
printf("After Swapping variable b=%d",b);
}

Output:
Before Swapping variable a: 3
Before Swapping variable b: 5
After Swapping variable a=5
After Swapping variable b=3

2.3 WAP to check whether the no is Even or Odd.

#include <stdio.h>
main()
{
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 10
11

int n;
printf("enter a number :");
scanf("%d",&n);
if(n%2==0)
{
printf("no is even\n");
}
else
{
printf("no. is odd\n");
}
}

Output:
Enter a number: 121
no. is odd.

2.4 WAP to calculate percentage and defines its grades using if else if ladder
statement.

If-Else-If ladder: When a series of many conditions have to be checked we may use
the ladder else if statement which takes the following general form.
If(cond1)
{
Statement1;
}else if(cond2)
{
Statement2;
}else if(cond3)
{
Statement3;
}else
{
Default statement;
}
This construct is known as if else construct or ladder. The conditions are evaluated
from the top of the ladder to downwards. As soon on the true condition is found, the
statement associated with it is executed and the control is transferred to the statement
– x (skipping the rest of the ladder. When all the condition becomes false, the final
else containing the default statement will be executed.

Source Code:
#include<stdio.h>
#include<conio.h>
main()
{
int sub1, sub2, sub3, sub4, sub5, tot, per;
printf("Enter Marks:");
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 11
12

scanf(“%d %d %d %d %d”,&sub1, &sub2, &sub3, &sub4, &sub5);


tot= sub1+sub2+sub3+sub4+sub5;
per = tot*100/500;
printf(“Percentage of student is = %d”,per);
if(per>=85)
{
printf(“Grade = A”);
}
else if(per>=70 && per<85)
{
printf(“Grade = B”);
}
else if(per>=55 && per<70)
{
printf(“Grade = C”);
}
else if(per>=40 && per<55)
{
printf(“Grade = D”);
}
else
{
printf(“Fail”);
}
getch();
}

Output:
Enter Marks: 35 45 55 65 75
Percentage of student is = 55
Grade = C

Experiment no. -02 Viva Voce Question


1.What are the basic data types in C.
Ans: Data types simply refers to the type and size of data associated
with variables and functions.

Data Types in c:
1.Fundamental Data Types
 Integer types
 Floating type
 Character type
2. Derived Data Types
 Arrays
 Pointers
 Structures
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 12
13

 Enumeration

 int - Integer data types


Integers are whole numbers that can have both positive and negative values but no
decimal values. Example: 0, -5, 10
In C programming, keyword int is used for declaring integer variable. For example:
int id;
Here, id is a variable of type integer.
 float – Floating data tyeps
Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can
declare a floating point variable in C by using either float or double keyword. For
example:
Float accountBalance;
double bookPrice;
Here, both accountBalance and bookPrice are floating type variables.

 char- character data type


Keyword char is used for declaring character type variables. For example:
char test = 'h';
Here, test is a character variable. The value of test is 'h'.
The size of character variable is 1 byte.

2. Define variables ,keywords, constant and identifiers?


Ans: Variables : In programming, a variable is a container (storage area) to hold
data.
Variable names are just the symbolic representation of a memory location. For
example:
int playerScore = 95;
Here, playerScore is a variable of integer type. The variable is assigned value: 95.

Keywords
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler.
For example:
int money;

Here, int is a keyword that indicates 'money' is a variable of type integer.


As C is a case sensitive language, all keywords must be written in lowercase.

Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program.
These fixed values are also called literals. Constants can be of any of the basic data
types like an integer constant, a floating constant, a character constant, or a string
literal. As mentioned, an identifier also can be defined as a constant.
const double PI = 3.14
Here, PI is a constant.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 13
14

Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique.
They are created to give unique
name to a entity to identify it
during the execution of the
program. For example:
int money;
double
accountBalance;
Here, money and acco untBalance
are identifiers.

3. Write down the basic rules


for defining variables?
Ans: Rules for naming a variable in C
 A variable must begin with a character or an underscore without spaces.
 The first letter of a variable should be either a letter or an underscore.
 The variable should not be a c keyword.
 The variable name should not start with a digit.

4.Explain if statement and if else statement with the help of syntax.


Ans: If statement: if statement is used for branching when a single condition is to
be checked. The condition enclosed in if statement decides the sequence of execution
of instruction. If the condition is true, the statements inside if statement are executed,
otherwise they are skipped. In C programming language, any non zero value is
considered as true and zero or null is considered false.

Syntax of if statement
if (condition)
{
statements;
... ... ...
}

Flowchart of if statement

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 14
15

If …else statement: If condition returns true then the statements inside the body of
“if” are executed and the statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped and
the statements in “else” are executed.
Syntax of if...else statement

if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}

Flow chart of if …else statement :

5. w.a.p to compare to variable using multiple if else statement .


Ans:We use multiple if statements to check more than one conditions.
#include <stdio.h>
void main()
{
int x, y;
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 15
16

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


scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}

printf("End of Program");
getch( );
}

Output:
enter the value of x:20
enter the value of y:20
x is equal to y
End of Program

EXPERIMENT NO. 3

Object: Programs to understand nested if-else statement and switch statement.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 16
17

Theory:- Nested if-else statement : When an if else statement is present inside the
body of another “if” or “else” then this is called nested if else.
switch statement: Switch case statements are a substitute for long if statements that
compare a variable to several integral values

3.1 WAP to print largest of three numbers.

#include <stdio.h>
int main()
{
double n1, n2, n3;

printf("Enter three numbers: ");


scanf("%lf %lf %lf", &n1, &n2, &n3);

if (n1>=n2)
{
if(n1>=n3)
printf("%.2lf is the largest number.", n1);
else
printf("%.2lf is the largest number.", n3);
}
else
{
if(n2>=n3)
printf("%.2lf is the largest number.", n2);
else
printf("%.2lf is the largest number.",n3);
}

return 0;
}

Output:
Enter three numbers: -4.5
3.9
5.6
5.60 is the largest number.

3.2 WAP to implement a simple calculator using switch case.

// Performs addition, subtraction, multiplication or division depending the input from


user
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 17
18

# include <stdio.h>

int main() {

char operator;
double firstNumber,secondNumber;

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


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber +
secondNumber);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber -
secondNumber);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber *
secondNumber);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber /
firstNumber);
break;

// operator doesn't match any case constant (+, -, *, /)


default:
printf("Error! operator is not correct");
}

return 0;
}

Output
Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 18
19

1.5 * 4.5 = 6

Experiment -03 Viva Voce Question

Q.1:- Elaborate the decision making statement supported by C.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 19
20

Ans:- Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Types of decision making statement.

A . if Statement B. if-Else Statement C. Nested If-Else Statement D. Ladder else - if


statement F. Switch case Statement

Q.2 Compare the use of the if-else statement with the use of the ?: operator?
Ans:- ?: this is called conditional operators and if-else is decision making statement.

Q.3 How are nested if else statements interpreted?


Ans:- Nested If-Else Statement :
It is a conditional statement which is used when we want to check more than 1
conditions at a time in a same program. The conditions are executed from top to
bottom checking each condition whether it meets the conditional criteria or not. If it
found the condition is true then it executes the block of associated statements of true
part else it goes to next condition to execute.

Syntax:

if(condition)
{
if(condition)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}

In above syntax, the condition is checked first. If it is true, then the program control
flow goes inside the braces and again checks the next condition. If it is true then it
executes the block of statements associated with it else executes else part.

Q.4 Explain break, statements in C with examples?

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 20
21

ANS: Break:- The break statement in C programming language has the following
two usages:

1. When the break statement is encountered inside a loop, the loop is


immediately terminated and program control resumes at the next statement
following the loop.
2. It can be used to terminate a case in the switch statement .

Syntax: The syntax for a break statement in C is as follows:


break;

Q.5 Explain switch case syntax .


Ans: A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for
each switch case.
The syntax for a switch statement in C programming language is as follows −

switch(expression)
{
case 1 :
statement(s);
break;
case 2 :
statement(s);
break;

default :
statement(s);
}

Experiment No. 4

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 21
22

Object: Programs to learn iterative statements like while and do-while loops.

Theory: In While looping statement allows a number of lines represent until the
condition is satisfied. In do-while loop first execute the statements then it checks the
condition.

4.1 WAP to print natural numbers using while loop.

#include <stdio.h>

int main()
{
int i, end;

/*
* Input a number from user
*/
printf("Print all natural numbers from 1 to : ");
scanf("%d", &end);

/*
* Print natural numbers from 1 to end
*/
i=1;
while(i<=end)
{
printf("%d\n", i);
i++;
}

return 0;
}

Output:
Print all natural numbers between 1 to :
10
1
2
3
4
5
6

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 22
23

7
8
9
10

4.2 WAP to print odd numbers using do while loop.

#include <stdio.h>

int main()
{
//loop counter declaration
int number;
//variable to store limit /N
int n;

//assign initial value


//from where we want to print the numbers
number=1;

//input value of N
printf("Enter the value of N: ");
scanf("%d",&n);

//print statement
printf("Odd Numbers from 1 to %d:\n",n);

//do-while loop, that will print numbers


do
{
//Here is the condition to check ODD number
if(number%2 != 0)
printf("%d ",number);

// increasing loop counter by 1


number++;
}while(number<=n);

return 0;
}
Output:
Enter the value of N: 10
Odd Numbers from 1 to 10:
13579

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 23
24

4.3 WAP to print sum of the digits of a number

#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,d;
printf("Enter the number:");
scanf("%d",&n);
while (n>0)
{
d=n%10;
sum=sum+d;
n=n/10;
}
printf("\n sum of digits= %d",sum);
printf("\n");
getch();
}

Output:
Enter the number: 15
Sum of digits= 6

Experiment -04 Viva Voce Question

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 24
25

Q.1 How many times will a for loop be executed?


Ans. Infinite time until condition not satisfied.
Q.2 What is meant by looping? Describe two different forms of looping?
Ans. Loops are used to repeat a block of code. Being able to have your program
repeatedly execute a block of code is one of the most basic but useful tasks in
programming -- many programs or websites that produce extremely complex output
(such as a message board) are really only executing a single task many times.
Q.3 Describe the loop Control structures in C? Explain with example?

Ans. There are three basic types of loops which are:

 “for loop”
 “while loop”
 “do while loop”

THE FOR LOOP:-

The “for loop” loops from one number to another number and increases by a specified
value each time.
The “for loop” uses the following structure:

for (Start value; continue or end condition; increase value)


statement;

WHILE LOOP:

In While looping statement allows a number of lines represent until the condition is
satisfied

Syntax:

while( condition)

Statement1;

...

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 25
26

Statement n;

DO WHILE LOOP:

In DO WHILE LOOP first execute the statements then it checks the condition.

Syntax:

do

Statement1;

...

Statement n;

}while(condition);

Q .4 How is execution of a while statement terminated?


Ans. In While loops Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the loop body.
Q.5 Explain differences between while and do-while loops.
Ans. in While loop the condition is tested first and then the statements are executed if
the condition turns out to be true.
In do while the statements are executed for the first time and then the conditions are
tested, if the condition turns out to be true then the statements are executed again.

Experiment No. 5

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 26
27

Object: Programs to understand for loops for iterative statements

5.1 WAP to print factorial of a number using for loop.

#include <stdio.h>
void main()
{
int i, fact = 1, num;

printf("Enter the number \n");


scanf("%d", &num);
if (num <= 0)
fact = 1;
else
{
for (i = 1; i <= num; i++)
{
fact = fact * i;
}
}
printf("Factorial of %d = %5d\n", num, fact);
}

Output:
Enter the number
10
Factorial of 10 = 3628800

5.2.1 WAP to print the pattern

*
**
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 27
28

***
* * * *.

Source Code:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j;
printf("Enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf(“*”);
}
printf(“\n”);
}
}

Output:
Enter the number: 4

*
**
***
****

5.2.2 WAP to print the pattern

****
***
**
*

Source Code:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j;
printf("Enter the number:");
scanf("%ld",&n);
for(i=1;i<=n;i++)

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 28
29

{
for(j=1;j>=i; j--)
{
printf(“*”);
}
printf(“\n”);
}
}

Output:
Enter the number: 4
****
***
**
*

Experiment -05 Viva Voce Question


Q.1 How many times will a for loop be executed?

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 29
30

Ans. Infinite time until condition not satisfied.


Q.2 What is meant by looping and also Describe the loop Control structures in
C?
Ans. A loop is a sequence of instructions that is continually repeated until a
certain condition is reached.

Ans. There are three basic types of loops which are:

 “while loop”
 “do while loop”
 “for loop”

Q.3 Differentiate between the Entry controlled and Exit controlled loops in C ?
Ans. In Entry controlled loop the test condition is checked first and if that condition is
true than the block of statement in the loop body will be executed while in exit
controlled loop the body of loop will be executed first and at the end the test condition
is checked, if condition is satisfied than body of loop will be executed again.
Q.4 What rules apply to the nesting of loops?
Ans. A nested loop is a logical structure used in computer programming where two
repeating statements are placed in a "nested" form, i.e., one loop is situated within the
body of the other. In this structure, the first iteration of the outer loop causes the inner
loop to execute. The inner loop then repeats for as many times as is specified. When
the inner loop completes, the outer loop is executed for its second iteration, triggering
the inner loop again, and so on until the requirements for the outer loop are complete.
Q.5 What will be the output of the following programs?
Main()
{
int i=1;
while(i<=10);
{
printf(“%d\n”,i);
i=i+1;
}
}
Ans. The output is :-
Error

Experiment No. 6
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 30
31

Object: Programs to learn about array and string operations.

6.1 WAP to add array elements of one dimensional array

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;

/* Input size of the array */


printf("Enter size of the array: ");
scanf("%d", &n);

/* Input elements in array */


printf("Enter %d elements in the array: ", n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}

/*
* Add each array element to sum
*/
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}

printf("Sum of all elements of array = %d", sum);

return 0;
}

Output:
Enter size of the array: 10s of array = 550
Enter size of the array: 5
Enter 5 elements:
12345
Sum of all elements of array = 15

6.2 WAP to find largest Element of Array.


DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 31
32

#include<stdio.h>

int main() {
int a[30], i, num, largest;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Read n elements in an array


for (i = 0; i < num; i++)
scanf("%d", &a[i]);

//Consider first element as largest


largest = a[0];

for (i = 0; i < num; i++) {


if (a[i] > largest) {
largest = a[i];
}
}

// Print out the Result


printf("\nLargest Element : %d", largest);

return (0);
}

Output :
Enter no of elements : 5
11 55 33 77 22
Largest Element : 77

6.3 WAP to ADD two Matrix using multi dimensional array.

#include <stdio.h>
int main(){
int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter number of rows (between 1 and 100): ");


scanf("%d", &r);
printf("Enter number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");

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


for(j=0; j<c; ++j)
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 32
33

{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &b[i][j]);
}

// Adding Two matrices

for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
sum[i][j]=a[i][j]+b[i][j];
}

// Displaying the result


printf("\nSum of two matrix is: \n\n");

for(i=0;i<r;++i)
for(j=0;j<c;++j)
{

printf("%d ",sum[i][j]);

if(j==c-1)
{
printf("\n\n");
}
}

return 0;
}
Output
Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 33
34

Enter element a11: 4


Enter element a12: 5
Enter element a13: 3
Enter element a21: 5
Enter element a22: 6
Enter element a23: 3

Sum of two matrix is:

2 8 7

10 8 6

Multiplication of two matrix:

#include <stdio.h>
main()
{
int a[2][3],b[3][2],c[2][2],i,j,k,sum=0;
printf(“Enter 6 values ”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]);
}
printf(“Enter 6 more values ”)
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf(“%d”,&b[i][j]);
}
for(i=0;i<2;i++)
{
for(k=0;k<2;k++)
{
for(j=0;j<3;j++)
sum=sum+a[i][j]*b[j][k];
c[i][k]=sum;
sum=0;
}
}
printf(“Multiplication of array ”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%d ”,c[i][j]);
printf(“\n”);
}
}
Output:
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 34
35

Enter 6 values 1 2 3 1 2 3
Enter 6 more values 1 2 1 2 1 2
Multiplication of array 6 12
6 12

6.4 WAP to print length of a string.

#include <stdio.h>
int main()
{
char s[1000];
int i;
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
printf("Length of string: %d", i);
return 0;
}

Output

Enter a string: Programiz

Length of string: 9

6.5 WAP to check whether a given string is palindrome or not.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 35
36

#include <stdio.h>

#include <string.h>

int main()

char a[100], b[100];

printf("Enter a string to check if it is a palindrome\n");

gets(a);

strcpy(b, a); // Copying input string

strrev(b); // Reversing the string

if (strcmp(a, b) == 0) // Comparing input string with the reverse string

printf("The string is a palindrome.\n");

else

printf("The string isn't a palindrome.\n");

return 0;

Output:

Enter a string to check if palindrome:

AbccbA

The string is palindrome

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 36
37

Experiment -06 Viva Voce Question

Q.1 Define Array? How many types of Arrays ?


Ans: Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element
in an array is accessed by an index.

There are three types of arrays in C,

1. Single Dimensional Array.


2. Multi dimensional Array

Q.2 Explain the dynamic and static array?


Ans. Static array is instantiated at compile time and exists for entire duration of
program.amount of memory allocated is fixed and can not be altered at run time.
Dynamic memory is instantiated at run time and exits until it is released
mannualy.Dynamic arrays are very useful when the length of an array is not known
when the program was written.

Q.3 What is the representation, Declaration, Definition of Single Dimensional


arrays and Multi dimensional array ?
Ans: Single Dimensional Array:
Single or One Dimensional array is used to represent and store data in a linear form.
 Array having only one subscript variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array.
Syntax:

<data-type> <array_name> [size];

Multi dimensional array:

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 37
38

1. Array having more than one subscript variable is called Multi-Dimensional array.

2. Multi Dimensional Array is also called as Matrix.

Syntax:

3. <data-type> <array_name> [row_subscript][column-subscript];

Q.4 Describe the Applications areas of Arrays ?


Ans. Array is used to store data or values of same type
These are applications of array-
1.Store elements of same type.
2.for maintaining multiple variables name using single name.
3.can be used for sorting elements.
4.can be used in CPU scheduling.
5.Can be used in recursion.

Q.5 How are array usually processed in C.


Ans. Array is processed by using concept of iteration.
for(i=0;i<3;i++){
scanf(“%d”,&arr[i])
}
The above for loop accepts the value from the user and stores it in an array.

Experiment No. 07

Object: Programs to understand sorting and searching using array

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 38
39

7.1 WAP to search a particular number in an array & print location.

#include <stdio.h>

int main()

int array[100], search, c, n;

printf("Enter number of elements in array\n");

scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)

scanf("%d", &array[c]);

printf("Enter a number to search\n");

scanf("%d", &search);

for (c = 0; c < n; c++)

if (array[c] == search) /* If required element is found */

printf("%d is present at location %d.\n", search, c+1);

break;

if (c == n)

printf("%d isn't present in the array.\n", search);

return 0;

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 39
40

Output:

Enter no of elements : 5

11 22 33 44 55

Enter the elements to be searched : 44

Number found at the location = 4

7.2 W.A.P to sort an array in ascending order.

#include <stdio.h>
void main()
{

int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);

printf("Enter the numbers \n");


for (i = 0; i < n; ++i)
scanf("%d", &number[i]);

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


{

for (j = i + 1; j < n; ++j)


{

if (number[i] > number[j])


{

a = number[i];
number[i] = number[j];
number[j] = a;

printf("The numbers arranged in ascending order are given below \n");


for (i = 0; i < n; ++i)
printf("%d\n", number[i]);

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 40
41

Output:
Enter the value of N: 6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780

Experiment -07 Viva Voce Question

1. Explain how to initialize and declare an array?


2. What is string in C? How it can be declared?
3. How to remove leading and trailing space from string?
4. Write code to print your name, class and college name using string.
5. Explain strcmp() and strcat() in C.

Experiment No. 08

Object: Programs to learn functions and recursive functions.


DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 41
42

8.1 WAP to print square of a number using user defined functions.

#include<stdio.h>

int Calculte_Square(int Number);

int main()
{
int number, Square;

printf(" \n Please Enter any integer Value : ");


scanf("%d", &number);

Square = Calculte_Square(number);

printf("\n Square of a given number %d = %d", number, Square);

return 0;
}

int Calculte_Square(int Number)


{
return Number * Number;
}

Output:

Enter your number:5


Square of 5 is 25.

8.2 WAP to check whether a given number is Armstrong or not using function.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 42
43

#include <stdio.h>
#include <math.h>

int checkArmstrongNumber(int n);


int main()
{
int n, flag;

printf("Enter a positive integer: ");


scanf("%d", &n);

// Check Armstrong number


flag = checkArmstrongNumber(n);
if (flag == 1)
printf("%d is an Armstrong number.", n);
else
printf("%d is not an Armstrong number.",n);
return 0;
}

int checkArmstrongNumber(int number)


{
int originalNumber, remainder, result = 0, n = 0, flag;

originalNumber = number;

while (originalNumber != 0)
{
originalNumber /= 10;
++n;
}

originalNumber = number;
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 43
44

while (originalNumber != 0)
{
remainder = originalNumber%10;
result += pow(remainder, n);
originalNumber /= 10;
}

// condition for Armstrong number


if(result == number)
flag = 1;
else
flag = 0;

return flag;
}

Output:

Enter a positive integer: 407

407 is an Armstrong number.

8.3 W.A.P to print Fibonacci series using recursion.

#include <stdio.h>

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 44
45

int fibo(int);

int main()
{
int num;
int result;

printf("Enter the nth number in fibonacci series: ");


scanf("%d", &num);
if (num < 0)
{
printf("Fibonacci of negative number is not possible.\n");
}
else
{
result = fibo(num);
printf("The %d number in fibonacci series is %d\n", num, result);
}
return 0;
}
int fibo(int num)
{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
return(fibo(num - 1) + fibo(num - 2));
}
}
Output:

Enter the nth number in fibonacci series: 8


The 8 number in fibonacci series is 21

8.4 W.A.P to swap two numbers using call by value & call by reference method.

#include <stdio.h>
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 45
46

/* Swap function definition */


void swap(int num1, int num2)
{
int temp;

printf("In Function values before swapping: %d %d\n", num1, num2);

temp = num1;
num1 = num2;
num2 = temp;

printf("In Function values after swapping: %d %d\n\n", num1, num2);


}

/* main() function definition */


int main()
{
int n1, n2;

/* Input two integers from user */


printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);

/* Print value of n1 and n2 in before swapping */


printf("In Main values before swapping: %d %d\n\n", n1, n2);

/* Function call to swap n1 and n2 */


swap(n1, n2);
printf("In Main values after swapping: %d %d", n1, n2);

return 0;
}

Enter two numbers: 10 20


In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 10 20

Call by reference:

#include <stdio.h>

/**
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 46
47

* *num1 - pointer variable to accept memory address


* *num2 - pointer variable to accept memory address
*/
void swap(int * num1, int * num2)
{
int temp;

printf("In Function values before swapping: %d %d\n", *num1, *num2);

temp = *num1;
*num1 = *num2;
*num2 = temp;

printf("In Function values after swapping: %d %d\n\n", *num1, *num2);


}

/* main() function declaration */


int main()
{
int n1, n2;

printf("Enter two numbers: ");


scanf("%d%d", &n1, &n2);

printf("In Main values before swapping: %d %d\n\n", n1, n2);

/*
* &n1 - & evaluate memory address of n1
* &n2 - & evaluate memory address of n2
*/
swap(&n1, &n2);

printf("In Main values after swapping: %d %d", n1, n2);

return 0;
}

Enter two numbers: 10 20


In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 20 10

Experiment -08 Viva Voce Question

Q1. Describe the Calling function and Called function?

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 47
48

Ans: Calling function is the function which calls the another function and the function
which is called is known as called function.

Q2. Differentiate between the Actual parameters /arguments and Formal


parameters/arguments?

Ans: Actual parameters are those parameters which are passed in functions as
arguments from calling function and formal parameters are those parameters which
are used in function body for the purpose of evaluating return value.

Q3. Explain the concept of pass by value / call by value?


Ans: Pass by value or call by value means the argument values are passed to the
called function.

Q4. Elaborate the concept of pass by reference / call by reference?


Ans: In pass by reference or call by reference instead of passing the value the refrence
to the variables is passed as arguments.

Q5. Define Recursion function?


Ans. A function that calls itself is known as a recursive function. And, this technique
is known as recursion.

void recursion( ) {

recursion( ); /* function calls itself */

int main( ) {

recursion( );

}
The C programming language supports recursion, i.e., a function to call itself. But
while using recursion, programmers need to be careful to define an exit condition
from the function, otherwise it will go into an infinite loop.

Experiment No. 09

Object: Programs to understand Structure and Union operation.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 48
49

Theory: Structure is collection of hetrogenous datatypes and array is collection of


similar data types.
A union is a special data type available in C that allows to store different data types in
the same memory location.

9.1 WAP to store information (Name, Roll and Marks) of a student using structure
and print.

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;

int main()
{
printf("Enter information:\n");

printf("Enter name: ");


scanf("%s", s.name);

printf("Enter roll number: ");


scanf("%d", &s.roll);

printf("Enter marks: ");


scanf("%f", &s.marks);

printf("Displaying Information:\n");

printf("Name: ");
puts(s.name);

printf("Roll number: %d\n",s.roll);

printf("Marks: %.1f\n", s.marks);

return 0;
}

Output

Enter information:
Enter name: Indrajeet
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 49
50

Enter roll number: 5147


Enter marks: 34.5
Displaying Information:
Name: Indrajeet
Roll number: 5147
Marks: 34.5

9.2 WAP to read book detail and print them using structure.

#include <stdio.h>

struct Bookinfo
{
char[20] bname;
int pages;
int price;
}book[3];

int main(int argc, char *argv[])


{
int i;

for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
gets(book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",book[i].price);
}

printf("\n--------- Book Details ------------ ");

for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}

return 0;
}

Output of the Structure Example:

Enter the Name of Book: ABC


DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 50
51

Enter the Number of Pages : 100


Enter the Price of Book : 200
Enter the Name of Book : EFG
Enter the Number of Pages : 200
Enter the Price of Book : 300
Enter the Name of Book : HIJ
Enter the Number of Pages : 300
Enter the Price of Book : 500

--------- Book Details ------------

Name of Book : ABC


Number of Pages : 100
Price of Book : 200
Name of Book : EFG
Number of Pages : 200
Price of Book : 300
Name of Book : HIJ
Number of Pages : 300
Price of Book : 500

9.3 WAP to implement union.

#include <stdio.h>
union Job
{
float salary;
int workerNo;
} j;

int main()
{
j.salary = 12.3;
j.workerNo = 100;

printf("Salary = %.1f\n", j.salary);


printf("Number of workers = %d", j.workerNo);
return 0;
}

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 51
52

Output:

Salary = 0.0

Number of workers = 100

Experiment -09 Viva Voce Question

Q.1 What is a structure? How does a structure differ from an array?


DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 52
53

Ans. Structure is collection of hetrogenous datatypes and array is collection of similar


data types.
Q.2 Describe the syntax for defining the composition of a structure.
Ans. A structure is a convenient way of grouping several pieces of related information
together.
struct mystruct
{
int numb;
char ch;
}

Structure has name mystruct and it contains two variables: an integer named numb
and a character named ch.

Q.3 How can structure variables be declared and it differ from structure type
declarations.
Ans. Structure variables are declared after the structure type declarations. Structure
variables are used to access the structure elements.
Q.4 Define Union. How does a union differ from a structures.
Ans.TO define a union you must use the union statement in the same way as we did
while defining a structure. The union statement define a new data type with more than
one member for your program. Size of structure is the sum of size of all element’s
datatypes while size of union is the maximum ofsize of elements datatype.

Q.5 What is the similarity between a Structure, Union and enumeration?


Ans. All of these are user defined data-types.

Experiment No. 10

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 53
54

Object: Programs to learn Pointer operations.


Theory: A pointer is a variable which contains the address in memory of another
variable.

10.1 WAP to print many values of a variable through pointers.

#include <stdio.h>
int main(){
int* pc;
int c;
c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
c=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
}
Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

10.2 WAP to perform pointer arithmetic operations.

#include <stdio.h>
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 54
55

int main()
{
int m = 5, n = 10, o = 0;

int *p1;
int *p2;
int *p3;

p1 = &m; //printing the address of m


p2 = &n; //printing the address of n

printf("p1 = %d\n", p1);


printf("p2 = %d\n", p2);

o = *p1+*p2;
printf("*p1+*p2 = %d\n", o);//point 1

p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2

p1++;
printf("p1++ = %d\n", p1); //point 3

p2--;
printf("p2-- = %d\n", p2); //point 4

//Below line will give ERROR


printf("p1+p2 = %d\n", p1+p2); //point 5

return 0;
}

p1 = 2680016
p2 = 2680012
*p1+*p2 = 15
p1-p2 = 1
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 55
56

p1++ = 2680020
p2-- = 2680008

10.3 WAP to add array elements of an array through pointers.

#include <stdio.h>

int main()
{
int data[5], sum=0,i;
printf("Enter elements: ");

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


scanf("%d", data + i);

printf("You entered: \n");


for(i = 0; i < 5; ++i)
sum=sum+ *(data+i);
printf("\n sum=%d", sum);

return 0;
}
Output
Enter elements: 1
2
3
4
5
Sum=15

Experiment -10 Viva Voce Question

Q.1 What is a pointer? How a pointer is declared?

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 56
57

Ans: A pointer is a variable which contains the address in memory of another


variable.
datatype *variable name;

Q2.Explain the pointers to arrays concept?


Ans: Pointer to array is same as pointer to any variable except the thing that pointer will
indicate the first element of array.

Q3.What is null pointer?


Ans: NULL Pointer is a pointer which points to nothing. NULL pointer points to base
address of segment. NULL keyword is used to assign null address.

Q4.Differentiate between const char* p and char const* p


Ans: Const char *p- p is a pointer variable pointing to constant character.
Char const *p- p is a constant pointer variable pointing to a char.

Q5.How can a function return a pointer to its calling routine?


Ans: return p

Experiment No. 11

Object: Programs to understand File handling operations.

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 57
58

Theory: File is permanent storage of data. It is a collection of bytes. It is the


process that sores and retrieves data in files.

11.1 .WAP to write a some of the character (without taking input from the
keyboard) and reading, printing , written characters.

#include< stdio.h >


int main()
{

FILE *fp; /* file pointer*/


char fName[20];

printf("\nEnter file name to create :");


scanf("%s",fName);

/*creating (open) a file*/


fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}

printf("File created successfully.");


/*writting into file*/
putc('A',fp);
putc('B',fp);
putc('C',fp);

printf("\nData written successfully.");


fclose(fp);

/*again open file to read data*/


fp=fopen(fName,"r");
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}

printf("Contents of file is :\n");


printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));

fclose(fp);
return 0;
}

Output:

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 58
59

Enter file name to create : ok.txt


File created successfully.
Data written successfully.
Contents of file is :
ABC

11.2 WAP to write a string to a file & print.

#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;

fptr = fopen("program.txt", "w");


if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter a sentence:\n");
gets(sentence);

fprintf(fptr,"%s", sentence);
fclose(fptr);

return 0;
}

Output:

Enter sentence:
I am awesome and so are files.

11.3 WAP to implement fprintf() & fscanf().

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 59
60

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char str[80], str1[80];

fp = fopen("data.txt","w");

if(fp == NULL)
{
printf("Cannot open file.\n");
exit(1);
}
printf("Enter string to be written in a file: ");
fscanf(stdin, "%s", str); /*Read from keyboard */

fprintf(fp, "%s", str); /*Write str to file */


fclose(fp);

fp = fopen("data.txt","r");

if(fp == NULL) {
printf("Cannot open file.\n");
exit(1);
}
fscanf(fp, "%s", str1); /* read a word from file and copy into
str1 */
fprintf(stdout, "%s", str1); /* print str1 on screen */
return 0;
}

Output:

Enter string to be written in a file: Hello


Hello

Experiment -11 Viva Voce Question

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 60
61

Q1.What is FILE?and What is file handling in c language? List out the different
modes of opening a file?
Ans: File is permanent storage of data. It is a collection of bytes. It is the process
that sores and retrieves data in files. Different modes of opening a file r, a ,w ,r+, a+,
w+

Q2.Distinguish between printf and fprintf.


Ans: fprintf is used to write inside a file while printf is used to print character stream
of data on stdout console.
Q3. What is getc and putc?
ANS: The getc() function returns the next character from the specified input stream
and increment file position indicator while The putc() function writes the character ch
to the specified stream at the current file position and then advance the file position
indicator
Q4.What is fread() and fscanf().
Ans: fscanf() function is used to read data from a file. While fread() function is used
to read data into a structure from a file.

Q5. What will be output of following program?


#include<stdio.h>
int main(){
printf("%d",EOF);
return 0;
}

ANS: -1

Experiment No. 12
DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB
Page | 61
62

Object: Programs to input data through Command line argument

#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {

printf("The argument supplied is %s\n", argv[1]);

else if( argc > 2 ) {

printf("Too many arguments supplied.\n");

else {

printf("One argument expected.\n");

Output:

$./a.out testing

The argument supplied is testing

DOHAS/LAB MANUAL/1FY3-24/ 2FY3-24 CP LAB


Page | 62

You might also like