0% found this document useful (0 votes)
12 views

Lab Report On C-Programming Lab No.: 1 To 12 Title: Introduction and Variables Date: 2079/01/16

1. The document is a lab report submitted by Anil Shah for labs 1 to 12 on C programming. It covers background theory on C programming, the basic structure of a C program, variables and their types, and summaries of the programs written for each lab. 2. Labs 1 to 12 involve writing programs to perform tasks like calculations, input/output, and displaying results. The programs cover basic C concepts like variables, data types, operators, conditional statements. 3. The report concludes with the programs written for each lab and their respective outputs. This provides a documentation of the programs written and experiments conducted in the labs.

Uploaded by

MICHEAL JACKSON
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lab Report On C-Programming Lab No.: 1 To 12 Title: Introduction and Variables Date: 2079/01/16

1. The document is a lab report submitted by Anil Shah for labs 1 to 12 on C programming. It covers background theory on C programming, the basic structure of a C program, variables and their types, and summaries of the programs written for each lab. 2. Labs 1 to 12 involve writing programs to perform tasks like calculations, input/output, and displaying results. The programs cover basic C concepts like variables, data types, operators, conditional statements. 3. The report concludes with the programs written for each lab and their respective outputs. This provides a documentation of the programs written and experiments conducted in the labs.

Uploaded by

MICHEAL JACKSON
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 199

`Lab Report on C-Programming

Lab No.: 1 to 12
Title: Introduction and Variables
Date: 2079/01/16

SUBMITTED BY: SUBMITTED TO:


Name: Anil Shah Department of Electronics and
Program: BAS Computer Engineering
Section: A Checked by: …………….
Roll No.: 077BAS002
• Background Theory:
The term programming refers to the process of giving instructions to the computer to
perform any specific task. Since computer is a machine which understands only
machine level language, the commands in human understandable form (source code)
must be converted into machine code (object code). Generally, there are two types of
programming languages: high level and low-level languages.
C is most powerful and widely used programming language which was
developed by Dennis M. Ritchie at Bell Telephone Laboratories, USA in 1972. Though
it is one of the oldest programming languages, its scope and importance in this
contemporary era is spellbinding and programmers are exploring it day by day across
the globe.
Compilation process is the process of converting the source code taken from
the user to object or machine code. The compilation process goes through four
following steps:
• Pre-processing
• Compiling
• Assembling
• Linking
• Basic Structure of C program:

#include<stdio.h>
int main()
{
printf(“Hello World”);
return 0;
}

• Difference between Compiler and Interpreter


Compiler Interpreter
Compiler scans and converts whole Interpreter converts the program
program statements into machine code at a statements into machine code one by one
time. at a time.
A compiler takes more time to analyze the An interpreter takes less time to analyze
source code. the source code.
It generates intermediate machine codes. It never produces any intermediate
machine codes.
Compiler is used by programming Interpreter is used by programming
languages like C, C++, Java and so on. languages like Python, PHP, Ruby and so
on.

• Difference between Software and Firmware


Software Firmware
Software is the collection of Firmware is a special type of software which is
program instructions that performs embedded in hardware device to control and run
the specific task. it properly.
It is written using low level and high It is written using low level languages.
level languages.
It is much easier to update the It is quite difficult to update firmware since it
software. may require reprogramming through a long
procedure.
Types of software include system Types of firmware include Legacy BIOS and
software and application software. UEFI.

• Variables and its Types:


Variables are the names given to store specific data in memory. The types of
variables used in C are:
• Local Variable
• Global Variable
• Static Variable
• Automatic Variable
• External Variable
LAB 1
1. Type the following program and see the output.
#include<stdio.h>
#include<conio.h>
void main(void)
{
printf(“This is my first C program.”);
getch();
}
OUTPUT:

2. Type the following program and run with different input.


#include<stdio.h>
#include<conio.h>
void main()
{
int s, a, b, c=20;
printf(“Enter the value of a:”);
scanf(“%d”,&a);
printf(“Enter value of b:”);
scanf(“%d”,&b);
s=a+b*c;
printf(“sum=%d”, s);
getch();
}
OUTPUT:
3. Type the following program and run and see the output.
#include<stdio.h>
#include<conio.h>
void main()
{
int s, a, b;
float p;
printf(“Address of s is %x”, &s);
printf(“\n Address of a is %x”, &a);
printf(“\n\n Occupied number of bytes by variable s is %d”, sizeof(s));
printf(“\n\n\n Size of a is %d”, sizeof(p));
printf(“\n\n\n\n Size of 1.5 is %d”, sizeof(1.5));
printf(“\n\n\n\n\n Size of float data type is %d”, sizeof(float));
getch();
}
OUTPUT:

4. Write a program to calculate the area, circumference of a circle of radius


r.
#include<stdio.h>
#include<conio.h>
void main()
{
float r, area, circum;
printf(“Enter a radius:”);
area=3.14*r^2;
circum=2*3.14*r;
printf(“Area of circle =%f”, area);
printf(“Circumference of circle =%f”, circum);
getch();
}
OUTPUT:

5. Write a program to calculate the volume of sphere of radius r.


#include<stdio.h>
#include<conio.h>
void main()
{
float r, vol;
printf(“Enter a radius:”);
scanf(“%f”,&r);
vol=(4*3.14*r*r*r)/3;
printf(“Volume of sphere is =%f”, vol);
getch();
}
OUTPUT:

6. Write a program to calculate the simple interest. Read values of P, T, R


from the user.
#include<stdio.h>
#include<conio.h>
void main()
{
float p, t, r, si;
printf(“Enter principal, time and rate:”);
scanf(“%f%f%f”,&p,&t,&r);
si=(p*t*r)/100;
printf(“The simple interest is =%f”, si);
getch();
}
OUTPUT:

7. Write a program to read values of x and y from the user and evaluate the
expression v=x +y -100/x;
3 2

#include<stdio.h>
#include<conio.h>
void main()
{
float x, y, v;
printf(“Enter the values of x and y:”);
scanf(“%f%f”,&x,&y);
v=x*x*x+y*y-100/x;
printf(“The value of v is =%f”, v);
getch();
}
OUTPUT:

8. Write a program to read four integers from the user and display mean of
the numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
float a, b, c, d, mean;
printf(“Enter the values of a, b, c and d:”);
scanf(“%f%f%f%f”,&a, &b, &c, &d);
mean=(a+b+c+d)/4;
printf(“The required mean is =%f”, mean);
getch();
}
OUTPUT:

9. Write a program to read l, b and h of a cuboid and display its volume.


#include<stdio.h>
#include<conio.h>
void main()
{
float l, b, h, vol;
printf(“Enter length, breadth and height of cuboid:”);
scanf(“%f%f%f”,&l, &b, &h);
vol=l*b*h;
printf(“The volume of cuboid is =%f”, vol);
getch();
}
OUTPUT:

10. Write a program to read price of two pens and five copies of same type
and calculate the price after discounting 10%.
#include<stdio.h>
#include<conio.h>
void main()
{
int pen, copy, price;
printf(“Enter the price of a pen and a copy:”);
scanf(“%d%d”,&pen, &copy);
price=2*pen+5*copy;
float finalpr=price-0.1*price;
printf(“The final price after discount is =%f”, finalpr);
getch();
}
OUTPUT:

11. Write a program to read time given for C programming study a day at
your home in hours, minutes and seconds and display the total time in
seconds in 30 days.
#include<stdio.h>
#include<conio.h>
void main()
{
float hr, min, sec;
printf(“Enter the time in hours, minutes and seconds:”);
scanf(“%f%f%f”,&hr, &min, &sec);
total=(hr*60*60+min*60+sec)*30;
printf(“The total time in seconds is =%f”, total);
getch();
}
OUTPUT:

12. Write a program to read name and age of a person and display them.
#include<stdio.h>
#include<conio.h>
void main()
{
char name[30]; int age;
printf(“Enter your name and age:”);
scanf(“%s%d”,&name, &age);
printf(“Your name is %s\nAge is %d”, name, age);
getch();
}
OUTPUT:

13. Write a program to read a character and display it.


#include<stdio.h>
#include<conio.h>
void main()
{
char c;
printf(“Enter a character: ”);
scanf(“ %c”, &c);
printf(“The entered character is %c”, c);
getch();
}
OUTPUT:

LAB 2

1. A program that inputs seconds as input and converts to minutes.


#include<stdio.h>
void main(void)
{
int seconds, min;
printf(“Enter number of seconds:”);
scanf(“%d”,&seconds);
min=seconds/60; /*integer division*/
seconds=seconds%60; /*integer division*/
printf(“\nMinutes=%d”,min);
printf(“\nSeconds=%d”,seconds);
}
OUTPUT:
2. A program to illustrate prefix increment operator.
#include<stdio.h>
void main()
{
int x=5,v;
v=++x*++x+++x;
printf(“v=%d,x=%d\n”,v,x);
}
OUTPUT:

3. A program to read three different integers from the user and display the
largest number from them.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,l;
clrscr();
printf(“Enter three different integers:”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b&&a>c)
l=a;
else if(b>a&&b>c)
l=b;
else
l=c;
printf(“Largest:%d”, l);
getch();
}
OUTPUT:

4. Type, compile, run and observe and think about the output of the
following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
clrscr();
x=30000, y=20000;
z=x+y;
printf(“Sum=%d”, z);
getch();
}
OUTPUT:

If the values of x=-30000 and y=-20000 then


5. Type, run and observe the output of the following program.

#include<stdio.h>
#include<conio.h>
void main()
{
float a; char b; long int c; unsigned int e;
clrscr();
printf(“Enter value of a”);
scanf(“%f”,&a);
printf(“Enter value of b:”);
scanf(“ %c”,&b);
printf(“Enter value of c and e”);
scanf(“%ld%u”,&c,&e);
printf(“value of a:%f\nvalue of b:%c\nvalue of c:%ld\nvalue of
e:%u”,a,b,c,e);
getch();
}
OUTPUT:

6. Write a program to convert the given Centigrade measure to Fahrenheit


using relation F=1.8C+32.
#include<stdio.h>
#include<conio.h>
void main()
{
float c,f;
printf(“Enter a temperature in centigrade”);
scanf(“%f”,&c);
f=1.8*c+32;
printf(“Temperature in Fahrenheit is=%f”, f);
getch();
}
OUTPUT:

7. Write a program to compute equivalent resistance of two resistors R and


1

R when they are connected in series and parallel connection.


2

#include<stdio.h>
#include<conio.h>
void main()
{
float r1,r2, series, parallel;
printf(“Enter values of two resistances R1 & R2”);
scanf(“%f%f”,&r1,&r2);
series=r1+r2;
parallel=r1*r2/(r1+r2);
printf(“The equivalent resistance in series is=%f”, series);
printf(“The equivalent resistance in parallel is=%f”, parallel);
getch();
}
OUTPUT:

8. Write a program to read two end points of a line, compute their mid point and
display it.
#include<stdio.h>
#include<conio.h>
void main()
{
float x1,x2,y1,y2,m1,m2;
printf(“Enter the first coordinate/point: ”);
scanf(“%f%f”,&x1,&y1);
printf(“Enter the second coordinate/point: ”);
scanf(“%f%f”,&x2,&y2);
m1=(x1+x2)/2;
m2=(y1+y2)/2;
printf(“\nThe coordinates of mid-point is=%.2f %.2f”, m1,m2);
getch();
}
OUTPUT:

9. Write a program to read number of girls and boys in your class and
display the ratio of girls to boys.
#include<stdio.h>
#include<conio.h>
void main()
{
float boys, girls;
float ratio;
printf(“Enter the number of boys: ”);
scanf(“%f”,&boys);
printf(“Enter the number of girls: ”);
scanf(“%f”,&girls);
ratio=girls/boys;
printf(“\nThe ratio of no. of girls to boys is=%.2f ”, ratio);
getch();
}
OUTPUT:

10. Write programs to evaluate the following expressions:


a. S=x +0.2xy+y
5 7

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x,y,S;
printf(“Enter the value of x: ”);
scanf(“%f”,&x);
printf(“Enter the value of y: ”);
scanf(“%f”,&y);
S=pow(x,5)+0.2*x*y+pow(y,7);
printf(“The calculated output is=%.2f ”, S);
getch();
}
OUTPUT:

b. f=(a+b) (2x+y)/(p-q) +c-100


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, x, y, p, q, c, f, power;
printf(“Enter the value of a, b, c, x, y, p, q: ”);
scanf(“%f%f%f%f%f%f%f”,&a,&b,&c,&x,&y,&p,&q);
power=(2*x+y)/(p-q);
f=pow((a+b),power)+c-100;
printf(“The calculated output is=%.3f ”, f);
getch();
}
OUTPUT:

c. r=A/B (A and B are integers)


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int A,B; float r;
printf(“Enter the value of A: ”);
scanf(“%d”,&A);
printf(“Enter the value of B: ”);
scanf(“%d”,&B);
r= (float) A/B;
printf(“The ratio is: %f ”, r);
getch();
}
OUTPUT:

d. r=(u/x+v/y) /(p /3u -q/2v)


5 2 2.5 3.5

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float u,v,x,y,p,q,r;
printf(“Enter the value of u, v, x, y, p, q: ”);
scanf(“%f%f%f%f%f%f”,&u,&v,&x,&y,&p,&q);
r= pow((u/x+v/y), 5)/pow((pow(p,2)/3*pow(u,2.5)-q/(2*v)),3.5);
printf(“The calculated value is: %f ”, r);
getch();
}
OUTPUT:

11. Write a program to swap values of two variables, say a and b.


#include<stdio.h>
#include<conio.h>
void main()
{
int a=15,b=20,t;
printf(“The value of a=%d and value of b=%d \n”,a,b);
t=a;
a=b;
b=t;
printf(“The value of a=%d and value of b=%d”, a,b);
getch();
}

OUTPUT:
• Analysis and Discussion:
In Lab 1 and Lab2, we built the fundamental concepts viz-variable, constants,
keywords, data types and so on. We introduced <math.h> header file to perform
mathematical calculations in easier way. We also analyzed the proper way of
using “printf” and “scanf” and overall the basic structure of C program which will
definitely help and encourage for building more conceptual and complex
programs further.

Lab No.: 3 & 4


Title: Console I/O & Branching Structures
LAB 3 : CONSOLE INPUT/OUTPUT
Background Theory:
Character I/O Character is one of the variable types in the C programming language. In
character Output we use printf("%c", character variable) Here I have used the variable
character variable which has the %c modifier to display the variable. In order to get or
input the variable we can use scanf("%c", &variable )where &variable is the address of
the variable the input is going to be taken and placed at that adress
String I/O String is treated as arrays of the characters in C we use the %s modifier to
display or modify a string in C programming, the similar approach may be used in order to
do that similar to the Character input output
Formatted Input Output Formated console input functions are used to take one or more
inputs from the user at the console. Those functions are called formatted console input
because we must specifiy format specifiers i.e. to read the primitive type of data and store
to a variable. There are two functions that are used in C programming for formatted input,
they are scanf() and sscanf(), scanf() is used to read one or multiple inputs from the user at
the console whereas the sscanf() functions is used to read the chaaracters from a string and
stores them in variables.
Limitation of scanf(): The great limitation of scanf function to read string is that it cannot
read the string having multiple words because %s terminates reading at the encounter of
any arbitrary white space. There are plural techniques to overcome this isuue/problem.
Search Set: Among different ways of reading string, the general format specifications are
%[characters] and %[^characters]. The specification %[characters] means that only
the characters specified within the brackets are permissible in the input string. The reading
of string will be terminated at the encounter of any other character in the input string. The
specification %[^characters] means exactly reverse of %[characters]. This means
characters specified after the circumflex(^) are not permitted in the input string. The
reading of the string will be terminated at the encounter of one of these characters. The set
of characters inside the brackets is called search set. Strings with white spaces can be read
using these specifications.

1. Write a program to read a character using getche()/getchar() and display


using putch()/putchar().
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
printf(“Enter a character: ”);
c=getchar();
printf(“Entered character is: ”);
putchar(c);
getch();
}
OUTPUT:
2. Write a program to read a character and a string using scanf() and
display printf().
#include<stdio.h>
#include<conio.h>
void main()
{
char c; char b[20];
printf(“Enter a character and a string: ”);
scanf(“%c%s”,&c,&b);
printf(“Entered character and a string is: %c %s ”, c,b);
getch();
}
OUTPUT:

3. Write a program to read a string using gets() and display using puts().
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
printf(“Enter a string: ”);
gets(name);
printf(“Entered string is: ”);
puts(name);
getch();
}
OUTPUT:
4. This example illustrates different format specifications for printing
integer numbers.
#include<stdio.h>
void main()
{
int a=12345;
printf(“\ncase 1 %d”,a);
printf(“\ncase 2 %i”,a);
printf(“\ncase 3 %15d”,a);
printf(“\ncase 4 %-15d”,a);
printf(“\ncase 5 %015d”,a);
printf(“\ncase 6 %-+15d”,a);
printf(“\ncase 7 %3d”,a);
}
OUTPUT:

5. This example illustrates different format specifications for printing real


numbers.
#include<stdio.h>
void main()
{
float n=123.9876;
printf(“\ncase 1 %f”,n);
printf(“\ncase 2 %e”,n);
printf(“\ncase 3 %g”,n);
printf(“\ncase 4 %15.4f”,n);
printf(“\ncase 5 %-15.3f”,-n);
printf(“\ncase 6 %015.4e”,n);
printf(“\ncase 7 %.8f”,n);
printf(“\ncase 8 %2.2f”,n);
}
OUTPUT:
6. This example illustrates different format specifications for printing
characters.
#include<stdio.h>
void main()
{
char ch=‘a’;
printf(“\nCase 1=%c”,ch);
printf(“\nCase 2=%10c”,ch);
printf(“\nCase 3=%-10c”,ch);
}
OUTPUT:

7. This example illustrates different format specifications for printing


strings.
#include<stdio.h>
void main()
{
char str[20]=”I love Baglung.”;
printf(“\nCase 1 %s”,str);
printf(“\nCase 2 %18s”,str);
printf(“\nCase 3 %-18s”,str);
printf(“\nCase 4 %18.8s”,str);
printf(“\nCase 5 %-18.9s”,str);
printf(“\nCase 6 %5s”,str);
printf(“\nCase 7 %.10s”,str);
}
OUTPUT:

8. This example illustrates the concept of printing mixed data.


#include<stdio.h>
#include<conio.h>
void main()
{
int n=12345;
float m=123.9876;
char ch=“a”;
char str[20]=”I love Baglung.”;
printf(“n=%7dm=%12.5fch=%-2cstr=%16s”,n,m,ch,str);
}
OUTPUT:

9. This example illustrates different format specifications for reading


integer numbers.
#include<stdio.h>
void main(void)
{
int a,b;
printf(“Enter an integer number:”);
scanf(“%d”,&a);
printf(“The read and stored value of a is =%d”,a);
printf(“Enter another integer number:”);
scanf(“%3d”,&b);
printf(“The read and stored value of b is =%d”,b);
}
OUTPUT:

10. This example illustrates the concept of reading strings using %wc
format specification.
#include<stdio.h>
void main(void)
{
char str[50];
printf(“Enter a string:”);
scanf(“%10c”,str);
printf(“Read string is:%s”,str);
}
OUTPUT:

11. This example shows the concept of defining search set to read strings.
#include<stdio.h>
void main()
{
char str[70];
printf(“How old are you:”);
scanf(“%[a-z0-9]”,str);
printf(“Read string is : %s”,str);

}
OUTPUT:
12. This example shows the concept of defining search set to read strings.
#include<stdio.h>
void main()
{
char str[70];
printf(“Enter a string:”);
scanf(“%[^M]”,str);
printf(“Read string is: %s”, str);
getch();
}
OUTPUT:

LAB 4 : BRANCHING STRUCTURES


Background Theory:
Simple If: The statements inside the body of “if” only execute if the given condition
returns true. If the condition returns false then the statements inside “if” are skipped.
Syntax of if statement:
if (condition)
{
//Block of C statements
//These statements will only execute if the condition is true
}
Nested If: A nested if in C is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes, both C and
C++ allow us to nested if statements within if statements, i.e, we can place an if
statement inside another if statement.
Syntax of nested if statement:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
If…else: The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the C else statement. We can use
the else statement with if statement to execute a block of code when the condition is
false.
Syntax of if else statement:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Nested If…else: When an if else statement is present inside the body of another “if” or
“else” then this is called nested if else.
Syntax of nested if…else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Switch: The switch case statement is used when we have multiple options and we need
to perform a different task for each option.
Syntax of switch case statement:
switch (variable or an integer expression)
{
case constant:
//C Statements
;
case constant:
//C Statements
;
default:
//C Statements
;
}

1. If a person’s age is greater than 65, he gets the seniority allowance. Write a
program to read the age of a person and display the appropriate message.

#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printf(“Enter your age:”);
scanf(“%d”,&age);
if (age>65)
printf(“You are eligible to get seniority allowance”);
else
printf(“You are not eligible to get seniority allowance”);

getch();
}
OUTPUT:

FLOWCHART
2. Write a program to read an integer from the user and check whether it is
positive, zero or negative and display the appropriate message on the screen.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf(“Enter an integer number “);
scanf(“%d”,&n);
if(n>0)
printf(“The number is positive);
else if(n==0)
printf(“The number is 0);
else
printf(“The number is negative”);
getch();
}
OUTPUT:

FLOWCHART
3. Write a program to read three sides of a triangle from the user and
calculate the area of the triangle. Be sure to check the condition of triangle
if sides are given.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,s,area;
printf("Enter any three sides of a triangle:");
scanf("%f%f%f",&a,&b,&c);
if((a+b)>c && (b+c)>a && (a+c)>b)
{
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("The area of triangle is=%f",area);
}
else
{
printf("Triangle cannot be formed from the given sides");
}
getch();
}
OUTPUT:

FLOWCHART
4.i. Write a program to read a character and check whether the character is
uppercase or lowercase.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“Enter a character ”);
ch=getchar();
if(ch>=65 && ch<=90)
printf(“\n Uppercase”);
if(ch>=97 && ch<=122)
printf(“\n Lowercase”);
getch();
}
OUTPUT:

FLOWCHART
4.ii. Write a program to read a character from user and convert it into
uppercase if it is lower and convert into lowercase if it is upper.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“Enter a character ”);
ch=getchar();
if(ch>=65 && ch<=90)
printf(“\n The converted character is %c”,ch+32);

else if(ch>=97 && ch<=122)


printf(“\n The converted character is %c”,ch-32);
else
printf(“\n Not a valid character”);
getch();
}
OUTPUT:

FLOWCHART
5. Write a program to read an unsigned integer and check whether the number is odd
or even. If it is even, check whether it is greater than 100 or not and display the
appropriate message. If the number is odd, check whether it is divisible by 11 but by 7
and display the appropriate message.
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int n,r;
printf("Enter an unsigned(+ve) integer ");
scanf("%d",&n);
r=n%2;
if(r==0){
if(n>100)
printf("\nThe number is even and greater than 100");
else
printf("\nThe number is even and less than 100");
}
else {
if(n%11==0){
if(n%7==0)
printf("\nThe number is odd and divisible by both 7 and 11");
else
printf("\nThe number is odd and divisible by 11 but not by 7");
}
else{
if(n%7==0)
printf("\nThe number is odd and divisible by 7 but not by 11");
else
printf("\nThe number is odd and neither divisible by 7 nor 11");
}
}
getch();
}
OUTPUT:

FLOWCHART
6. Write a program to determine all roots of a quadratic equation ax +bx+c=0.
2

Read the values of a, b and c from the user.


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,d,q,w,x1,x2;
printf("Enter the coefficients of quadratic equations a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
printf("\nReal and equal roots are x1=%f and x2=%f",-b/(2*a),-b/(2*a));
else if(d>0)
{
printf("\n Real and unequal roots are:");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("x1=%f and x2=%f", x1,x2);
}
else{
d*=-1;
q=-b/(2*a);
w=sqrt(d)/(2*a);
printf("The imaginary roots are: x1=%f+%fi and x2=%f-%fi",q,w,q,w);
}
getch();
}
OUTPUT:

FLOWCHART
7. Write a program to evaluate the following function f(x) given by:
=0 if x≤0
=x(x-10)(x-15) if 0<x≤10
f(x) =(x-10)(x-15)(x-20) if 10<x≤15
=(x-15)(x-20)(x-30) if 15<x≤20
=(x-20)(x-30)(x-40) if 20<x≤30
=0 for all other cases
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf("Enter the value of x: ");
scanf("%d",&x);
if (x<=0)
printf("\nValue of f(x) = 0");
else if (x>0 && x<=10)
printf("\n Value of f(x) = %d",x*(x-10)*(x-15));
else if (x>10 && x<=15)
printf("\nValue of f(x) = %d",(x-10)*(x-15)*(x-20));
else if (x>15 && x<=20)
printf("\nValue of f(x) = %d",(x-15)*(x-20)*(x-30));
else if (x>20 && x<=30)
printf("\nValue of f(x) = %d",(x-20)*(x-30)*(x-40));
else
printf("\nValue of f(x) = 0");
getch();
}
OUTPUT:

FLOWCHART
8. Write a program that prompts the user to enter any integer from 1 to 7 and displays the
corresponding day of the week.
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
printf(“Enter a number from 1 to 7: ”);
scanf(“%d”,&day);

switch(day){
case 1:
printf(“\n Sunday”);
break;
case 2:
printf(“\n Monday”);
break;
case 3:
printf(“\n Tuesday”);
break;
case 4:
printf(“\n Wednesday”);
break;
case 5:
printf(“\n Thursday”);
break;
case 6:
printf(“\n Friday”);
break;
case 7:
printf(“\n Saturday”);
break;
}
getch();
}
OUTPUT:

FLOWCHART
9. Write a program that asks an arithmetic operator and two operands and performs the
corresponding operation on the operands.
#include<stdio.h>
#include<conio.h>
void main()
{
char op;
float num1,num2;
printf("Enter any two numbers:");
scanf("%f%f",&num1,&num2);
printf("\n Enter the arithmetic operator:");
scanf(" %c",&op);
switch(op)
{
case '+':
printf("\n num1 + num2=%f",num1+num2);
break;

case '-':
printf("\n num1 - num2=%f",num1-num2);
break;

case '*':
printf("\n num1 * num2=%f",num1*num2);
break;

case '/':
printf("\n num1 / num2=%f",num1/num2);
break;

default:
printf("\n Enter a valid operator !");
break;
}
getch();
}
OUTPUT:
FLOWCHART

10. “You are given a task to develop a system to read at least 100 integer
numbers and continue until the user enters No. Your system must have
capacity to calculate the sum and average of those numbers which are exactly
divisible by 9 but not by 6 and lies in between 1 to 100 and display a suitable
message if no such number is read”. Write algorithm, flowchart and code to
develop such system.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, sum=0,avg ,i=0;
printf("Enter an integer number ");
while(a!=0){
scanf("%d",&a);
if(a%9==0 && a%6!=0 && a>1 && a<100)
{
i+=1;
sum+=a;
}
}
avg=sum/i;
printf("Sum is = %d",sum);
printf("\nAverage is=%d",avg);
getch();
}
OUTPUT:

ALGORITHM
Step 1: Start
Step 2: Declare variables a, i, avg, sum
Step 3: Initialize sum = 0 and i=0
Step 4: Read value of a
Step 5: If(a≠=0)
Repeat steps 5.1 and 5.2 while(a mod 9=0 & a mod 6≠0 & a>1 & a<100)
5.1 i=i+1
5.2 sum=sum+a
else
avg=sum/i
Step 6: Print sum
Step 7: Print avg
Step 8: Stop

FLOWCHART
11. Make a list of operators available in C with their precedence and
associativity. Identify difference between switch and else if ladder structures.
Operator Operation Precedence Associativity
() Functional call 1 Left to right
[] Array element reference
-> Indirect member selection
. Direct member selection
| Logical negation 2 Right to left
~ Bitwise( 1`s) complement
+ Unary plus
- Unary minus
++ Preincrement or postincrement
-- Predecrement or postdecrement
& Address
* Pointer reference(indirection)
sizeof Returns the size of an object in bytes
(type) Type cast (conversion)
* Multiply 3 Left to right
/ Divide
% Remainder(modulus)
+ Binary plus(addition) 4 Left to right
- Binary minus(subtraction)
<< Left shift 5 Left to right
>> Right shift
< Less than 6 Left to right
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to 7 Left to right
|= Not equal to
& Bitwise AND 8 Left to right
^ Bitwise exclusive XOR 9 Left to right
| Bitwise OR 10 Left to right
&& Logical AND 11 Left to right
|| Logical OR 12 Left to right
?: a? x : y means “if a then x, else y”. 13 Left to right
= Simple assignment 14 Right to left
*= Assign product
/= Assign quotient
%= Assign remainder (modulus)
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
Comma Separator as in int a,b,c; 15 Left to right

Difference between Switch and Else if ladder


S.N. SWITCH ELSE IF
1. In case of switch case, as per the In else if ladder, the control goes
value of the switch, the control through the every else if statement
jumps to the corresponding case. until it finds true value of the
statement or it comes to the end of
the else if ladder
2. Switch case statement works on Else if ladder statement works on the
the basis of equality operator. basis of true false or zero/non-zero.
3. Switch case statement is flexible Else if statement is not flexible
because it gives room for testing because it does not give room for
of a single expression against a list testing of a single expression against
of discrete values. a list of discrete values.
4. In switch, break statement is In else if ladder, the use of break
mandatory and very important. statement is not very essential.
5. Switch case is used when there is Else if ladder is used when there is
only one condition and multiple multiple conditions are to be tested.
values of the same are to be
tested.

• Analysis and Discussion:


In Lab 3, we learnt about the use of getche()/getchar() and gets() to read
characters and strings(combination of characters) instead of using only scanf function.
We built the base for printing integer, real numbers, characters and strings using
different format specifications. The concept of defining search set helped to define
print the characters according to requirement.
From Lab 4, we formally opened the door of distinct loops viz- if, nested
if, if….esle, nested if…else, if…else….if….else and switch case structures(No. 8 & 9).
We concluded that the use of if , if….else are better but the use of switch structure
made program more feasible and it is more advanced form of other looping structures.
Lab No.: 5 & 6
Title: Repetitive Structures and Nested Loop Structures

LAB 5 : REPETITIVE STRUCTURE (LOOPING, ITERATION)


For Loop: A loop is used for executing a block of statements repeatedly until a given
condition returns false.
Syntax of for loop:
for (initialization; condition test; increment or decrement)
{
//Statements to be executed repeatedly
}
While Loop: A while loop is used for executing a block of statements repeatedly until a
given condition returns false.
Syntax of while loop:
while (condition test)
{
//Statements to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}
Do….While Loop: A do while loop is similar to while loop with one exception that it
executes the statements inside the body of do-while before checking the condition. On the
other hand in the while loop, first the condition is checked and then the statements in
while loop are executed. So you can say that if a condition is false at the first place then
the do while would run once, however the while loop would not run at all.
Syntax of do….while loop:
do
{
//Statements

}while(condition test);
Nested for Loop: The nested for loop means any type of loop which is defined inside the
'for' loop.
Syntax of nested for loop:
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}
Nested while Loop: The nested while loop means any type of loop which is defined
inside the 'while' loop.
Syntax of nested while loop:
while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}
Nested do…while Loop: The nested do..while loop means any type of loop which is
defined inside the 'do..while' loop.
Syntax of nested do…..while loop:
do
{
do
{
// inner loop statements.
}while(condition);
// outer loop statements.
}while(condition);
Break:
1. It is used to come out of the loop instantly. When a break statement is encountered
inside a loop, the control directly comes out of loop and the loop gets terminated. It is
used with if statement, whenever used inside loop.
2. This can also be used in switch case control structure. Whenever it is encountered in
switch-case block, the control comes out of the switch-case.
Syntax of break:
break;
Continue: The continue statement is used inside loops. When a continue statement is
encountered inside a loop, control jumps to the beginning of the loop for next iteration,
skipping the execution of statements inside the body of loop for the current iteration.
Syntax of continue:
continue;

Goto structures: When a goto statement is encountered in a C program, the control jumps
directly to the label mentioned in the goto statement.
The goto statement is rarely used because it makes program confusing, less readable and
complex. Also, when this is used, the control of the program won’t be easy to trace, hence
it makes testing and debugging difficult.
Syntax of goto:
goto label_name;
..
..
label_name: C-statements
Exit() function: In the C Programming Language, the exit function calls all functions
registered with atexit and terminates the program. File buffers are flushed, streams are
closed, and temporary files are deleted. The exit function does not return anything.
Syntax of exit:
void exit(int status);

1. Run the following programs and observe/comment the output.


a. int main()
{
int i;
clrscr();
for(i=0;i<=255;i++)
printf(“%d=%c\t”,i,i);
getch();
return 0;
}
OUTPUT:

b. int main()
{
int a=10;
clrscr();
printf(“%d”,a);
a=a+50;
printf(“%d”,a);
return 0;
}
OUTPUT:

2. Write a program to read an unsigned integer (suppose n) and display from 1


to n and n to 1.
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int n,i,j;
printf("Enter a positive integer ");
scanf("%u",&n);
for(i=1;i<=n;i++)
printf("%u\t",i);
printf("\n");
for(j=n;j>=1;j--)
printf("%u\t",j);
getch();
}
OUTPUT:

FLOWCHART
3. Write a program to display sum of even numbers from 1 to n. [n is an
unsigned integer]
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int i,n,sum=0;
printf("\n Enter any unsigned integer:");
scanf("%u",&n);

for(i=1;i<=n;i++)
{
if(i%2==0){
sum+=i;
printf("%u\n",i);
}
}
printf("Sum of even numbers= %u",sum);
getch();
}
OUTPUT:

FLOWCHART
4. Write a program to read an integer (suppose n) and find product from 1 to n
if n is even else find the sum from 0 to n.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,mul=1,sum=0;
printf("Enter an integer number ");
scanf("%d",&n);

if(n>=0){
if(n%2==0){
for(i=1;i<=n;i++)
mul=mul*i;
printf("\nThe product from 1 to %d = %d",n,mul);
}
else{
for(j=0;j<=n;j++)
sum+=j;
printf("\nThe sum from 0 to %d = %d",n,sum);
}
}
else
printf("Enter a valid integer number");
getch();
}
OUTPUT:

FLOWCHART
5. Write a program to read an integer, compute its factorial and display.
Display appropriate message if its factorial cannot be computed.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,fact=1;float n;
printf("\n Enter the number whose factorial has to be computed:");
scanf("%f",&n);
if(n-(int)n==0)
{
if(n>0){
for(i=1;i<=n;i++)
fact*=i;

printf("Factorial of %f = %d",n,fact);
}

else if(n==0)
printf("Factorial of 0 is 1");

else
printf("Enter a positive number");
}
else
printf("Enter an integer number");

getch();
}
OUTPUT:

FLOWCHART
6. Write a program to calculate x /n!. Where x is a floating-point number and n
n

is an integer greater or equal to 0.


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x,r,p;
int i,n,fact=1;
printf("\n Enter the value of x and n ");
scanf("%f%d",&x,&n);

for(i=1;i<=n;i++)
fact*=i;
p=pow(x,n);
r=p/fact;
printf("The value of %.3f^%d/%d! is %.3f",x,n,n,r);
getch();
}
OUTPUT:

FLOWCHART
7. Write a program to display the terms of a Fibonacci sequence: 0, 1, 1, 2, 3, 5,
8, 13…..
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,first_term=0, second_term=1,term;
printf("%d\t%d\t",first_term,second_term);
for(i=1;i<=6;i++)
{
term=first_term+second_term;
first_term=second_term;
second_term=term;
printf("%d\t",term);

}
printf(".....");
}
OUTPUT:

FLOWCHART
8. Write a program to read a positive integer and find the sum of digits in it.
For example, if the entered number is 345, then the result must be 3+4+5=12.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0, rem;
long int num;
printf("Enter an integer number ");
scanf("%ld",&num);
if(num>0){
do{
rem=num%10;
sum+=rem;
num/=10;
} while(num!=0);
printf("\nThe sum is = %d",sum);
}
else
printf(“\nNot a valid number”);
getch();
}
OUTPUT:

FLOWCHART
9. Write separate programs to check whether an unsigned integer entered
by the user is a palindrome, Armstrong, prime, twin prime.
Palindrome
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int n;
int r,sum=0,temp;
printf("Enter the value of n:");
scanf("%u",&n);
temp=n;
while (n>0)
{
r=n%10;
sum=sum*10+r;
n=n/10;
}
n=temp;
if(n==sum)
printf("\nPalindrome number");
else
printf("\nNot Palindrome");
}
OUTPUT:

FLOWCHART
Armstrong
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int n;
int r,c,sum=0,temp;
printf("Enter the value of n:");
scanf("%u",&n);
temp=n;
while (n>0)
{
r=n%10;
c=r*r*r;
sum=sum+c;
n=n/10;
}
n=temp;
if(n==sum)
printf("\nArmstrong");
else
printf("\nNot Armstrong");
}
OUTPUT:

FLOWCHART
Prime
#include<stdio.h>
#include<conio.h>
void main()
{
int i,count=0; unsigned int n;
printf("Enter a positive number ");
scanf("%u",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
printf("\nThe number is prime");
else
printf("\nThe number is not a prime");
getch();
}
OUTPUT:

FLOWCHART
Twin Prime
#include<stdio.h>
#include<conio.h>
int prime(int num)
{
int f=0,i;
for(i=2;i<num;i++)
{
if(num%i==0)
{
f=1;
break;
}
}
if(f==0)
return 1;
else
return 0;
}
int main()
{
int num1,num2,i;
printf("Enter starting number ");
scanf("%d",&num1);
printf("Enter last number ");
scanf("%d",&num2);
if(num1<=1)
{
num1=2;
}
for(i=num1;i<=num2;i++)
{
if(prime(i)==1 && prime(i+2)==1)
{
printf("%d %8d\n",i,i+2);
}
}
}
OUTPUT:
10. Write a program to read a number(n) and display its multiplication
table up to 10. For example, if value of n is 5 the output must be as follows:
1*5=5
2*5=10
3*5=15
4*5=20
5*5=25
6*5=30
7*5=35
8*5=40
9*5=45
10*5=50
#include<stdio.h>
#include<conio.h>
int main(){
int num,i;
printf("Enter the number whose multiplication table is to be printed\n");
scanf("%d",&num);
printf("The multiplication table of %d is\n",num);
for(i=0;i<10;i++)
printf("%d x %d = %d\n",i+1,num,(i+1)*num);
return 0;
}
OUTPUT:

FLOWCHART
LAB 6 : NESTED LOOP STRUCTURE

1. Write a program to print a multiplication table of MxN. Read values of M and


N from the user.
#include<stdio.h>
#include<conio.h>
int main(){
int num,num1,i;
printf("Enter the number whose multiplication table is to be printed\n");
scanf("%d",&num);
printf("Enter the number upto which multiplication table is to be printed\n");
scanf("%d",&num1);
printf("The multiplication table of %d is\n",num);
for(i=1;i<=num1;i++)
printf("%d x %d = %d\n",i,num,i*num);
return 0;
}
OUTPUT:

2. Write a program to display the chessboard pattern. [Hint: print “\xdb” for white
color and print “ ” for black color.]
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=1;i<=8;i++)
{
for(j=1;j<=8;j++)
{
if ((i+j)%2==0)
printf("\xdB");
else
printf(" ");
}
printf("\n");
}
getch();
}
OUTPUT:

3. Write a program to read two integers (n1 and n2, both positive and
n1<n2) from the user and display the prime and palindrome numbers
between n1 and n2. Display their counts also.
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int n1,n2;
int count=0,i,j,sum=0,temp;
printf(“Enter any two positive integers ”);
scanf(“%d”,&n1,&n2);
if(n1>0 && n2>0)
{
for(i=n1;i<=n2;i++)
{
count++;
n1+=1;
if(n1%i==0)
printf(“%d”,num);
}
}
for(j=n1;j<=n2;j++)
temp=j;
while(j>0)
{
r=j%10;
sum=sum*10+r;
j/=10;
}
j=temp;
printf(“%d”,j);
printf(“The count of numbers is %d”,count
}

4. Write a program to find the sum of all positive numbers entered by the
user. Read numbers and keep calculating the sum until the user enters 0.
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int n; int sum=0;
printf("Enter a positive number: \n");

while(n!=0)
{
scanf("%u",&n);
sum+=n;
}
printf("\nThe sum is: %d",sum);
getch();
}
OUTPUT:
5. Write separate programs to display the terms of the following sequences
upto nth term:
a. 1 , 2 , 3 , 4 , 5………n
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("Enter the value of n: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d, ",i);
}
OUTPUT:

b. 2 , 4 , 6 , 8 , 10 , 12 , 14, ………2n
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("Enter the value of n: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d, ",2*i);
}
OUTPUT:
c. 1 , 2 , 5 , 10 , 17 , 26 ………
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("Enter the value of n: ");
scanf("%d",&n);
for(i=0;i<=n;i++)
printf("%d, ",i*i+1);
}
OUTPUT:

d. (1 +2 )/2 , (2 +3 )/3 , (3 +4 )/4, ………


2 2 2 2 2 2

#include<stdio.h>
#include<conio.h>
void main()
{
float x,n,i;
printf("Enter the value of n: ");
scanf("%f",&n);
for(i=1;i<=n;i++){
x=(i*i+(i+1)*(i+1))/(i+1);
printf("(%.0f^2+%.0f^2)/%.0f= %.3f,\t",i,i+1,i+1,x);
}
}
OUTPUT:

e. 1 , 1/3 , 1/5 , 1/7 , 1/9, 1/11 , 1/13 ………1/2n-1


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("Enter the value of n: ");
scanf("%d",&n);
printf("1,\t");
for(i=2;i<=n;i++)
printf("1/%d,\t",2*i-1);
}
OUTPUT:

6. Write separate programs to evaluate the series upto nth term:


a. s=2+4+6+8+10+12+14…….2n
#include<stdio.h>
#include<conio.h>
int main()
{
int i, n, s, sum=0;
printf("Enter upto which term sum is to be calculated: \n");
scanf("%d",&n);
for(i=1;i<=n-1;i++){
s=2*i;
sum+=s;
printf("%d + ",s);
}
printf("%d = %d",2*i,sum+2*i);
return 0;
}
OUTPUT:
b. S=e =1- 1/1! + 1/2! - 1/3! + 1/4! - 1/5!......(-1) /(n-1)!, n=1,2,3….
-1 n+1

#include<stdio.h>
#include<conio.h>
int main()
{
int n;
float i,sign=1,fact=1;
float sum=1,term;
printf("Enter the number of terms: ");
scanf("%d",&n);
printf("\t1");
for(i=1;i<n;i++){
fact=1;
fact=fact*i;
sign*=-1;
term=sign*(1/fact);
sum=sum+term;
printf("\t %.0f/%.0f",sign,fact);
}
printf("\n\nThe sum is: %.5f",sum);
return 0;
}
OUTPUT:
c. f(x)=1 - x /2! + x /4! - x /6! + x /8!.........(-1) x /2i! where i=0,1,2,3……
2 4 6 8 i 2i

#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
int i, j, n, sign = -1, den;
float x, sum = 0, num, term;
printf("Enter value of x in radian and number of terms n:");
scanf("%f%d", &x, &n);
if (x != 0)
{
for (i = 0; i < n; i++)
{
sign *= -1;
num = pow(x, 2 * i);
printf("\n %f\n", num);
den = 1;
for (j = 1; j <= 2 * i; j++)
den *= j;
term = sign * (num / den);
sum += term;
}
printf("f(%f)=%f", x, sum);
}
else{
printf("f(%f)=1",x);
}
getch();

}
OUTPUT:

7. Write a program to evaluate the series until the term becomes less than
10 .-6

s =1+x/1!+x /2!+x /3!...........


n
2 3

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, den,n;
float term, sum=0, x;
printf(“Enter the value of n and x: ”);
scanf(“%d %f”,&n,&x);
for(i=0;i<=n;i++){
num=pow(x,i);
den=1;
for(j=1;j<=i;j++){
den*=j;
}
while(term>0.000001)
term=num/den;
sum+=term;
printf(“%f”,&term);
}
printf(“The sum is=%f”,sum);
}
8. Write separate program to print the following patterns using nested loop
structures.
A. 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=1;i<=5;i++){
printf("\n");
for(j=1;j<=i;j++)
printf("%d ",j);
}
}
OUTPUT:
B. 5 4 3 2 1
5 4 3 2
5 4 3
54
5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=1;i<=5;i++){
printf("\n");
for(j=5;j>=i;j--)
printf("%d ",j);
}
}
OUTPUT:
C. N
E E
P P P
A A A A
L L L L L
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
char ch[6]="NEPAL";
char k;
for(i=0;i<=4;i++){
printf("\n");
for(j=0;j<=i;j++){
k=ch[i];
printf("%c ",k);
}
}
}
OUTPUT:
D. A
A B
A b C
A B C D
A b C d E
#include<stdio.h>
#include<conio.h>
void main()
{
char name[]=“ABCDE”;
char name2[]=“Abcde”;
for(int i=1;i<=5;i++){
for(int j=0;j<=i-1;j++){
if((i+j)%2!=0){
printf(“%c\t”,name[j]);
}
else
printf(“%c\t”,name2[j]);
}
printf(“\n”);
}
}
OUTPUT:
E. # # # # *
# # # * *
# # * * *
# * * * *
* * * * *
#include<stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
for(j=4;j>=0;j--)
{
if(j>=i)
printf(" # ");
else
printf(" * ");
}
printf("\n");
}
return 0;
}
OUTPUT:
F. 4
3 4
2 3 4
1 2 3 4
2 3 4
3 4
4
#include <stdio.h>
#include <conio.h>
void main() {
int rows = 4, cols = 4, i, j;
for(i = rows; i>=1; --i)
{
for(j = i; j >1; --j)
printf(" ");
for(j = i; j<=rows; ++j)
printf("%d ", j);
printf("\n");
}
for(i = 2; i<=rows; ++i)
{
for(j = i; j >1; --j)
printf(" ");
for(j = i; j<=rows; ++j)
printf("%d ", j);
printf("\n");
}
}
OUTPUT:
G. * * * * * * *
* * * * *
* * *
*

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n=4,z=2*n-1,sp,k;
for(i=n;i>=1;i--){
printf("\n");
for(sp=n-1;sp>=i;sp--){
printf(" ");
}
for(k=1;k<=z;k++){
printf("* ");
}
z-=2;
}
}
OUTPUT:
• Analysis and Discussion:
In Lab 5, we mostly used for, while and do….while loop structures to
solve various problems. Here, we coped with problems using such loops which
executes multiple times to display the desired result.
In Lab 6, we used while, do…while and nested for loops(for inside for)
for printing various series, sum of series and number as well as character patterns.
One new thing that we learnt in this lab while doing chessboard problem is “\xdb”
is used for printing square like small box in white colour.
Lab No.: 7 & 8
Title: User Defined Functions and 1D & 2D Arrays

LAB 7 : USER DEFINED FUNCTIONS


Background Theory:
Advantages of functions:
i.Since the program breaks up into different smaller sections or parts, it makes programs
significantly easier to understand and maintain. The main program can consist of a
series of function calls rather than countless lines of code.
ii.The well managed and written function codes can be reused in multiple programs. The
C standard library is an example of reuse of functions.
iii.Another benefit of using functions in programs is that different programmers working
on one large project can divide the workload by writing different functions.
iv.Programs that use functions are easier to design, program, debug and maintain.
Function declaration or prototype:
A function declaration provides the following information to the compiler:
• Name of the function
• The type of value returned (optional, integer type is default)
• Number of arguments that must be supplied in a call to the function.
• Type of arguments that must be supplied in a call to the function.
Function definition: A function definition in C programming language consists of
function name, function parameters, return value and function’s body.
Syntax:
return_type function_name(type arg1, type arg2 .....) {
body of a function
return (expression);
}
Function call: While creating a C function, you give a definition of what the function
has to do. To use a function, you will have to call that function to perform the defined
task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
Return_type : The return_type is the data type of the value returned by the function. Void data
type is used when the function does not return any value. By default the return type of a
function is integer(int).
return(expression) : This is used to send a value to calling function before termination of
function. If the return type of function is void, you need not use this line. When control
reaches return statement, it halts the execution of function immediately and returns the
value of expression to calling function.
Types of user defined functions in C
• Functions with no arguments and no return values:
void functionName() //Return type in the function header should be ‘void’
{
........
........
}
• Functions with no arguments and with return values:
returnType functionName()
{
....
....
return value;
}
• Functions with arguments and no return values:
void functionName(typel argl, type2 arg2,...... typeN argN)
{
....
....
}
• Functions with arguments and with return values:
returnType functionName(typel argi, type2 arg2,.........typeN argN)
{
....
....
return value;
}
Call by Value: This method copies the actual value of an argument into the formal parameter
of the function. In this case, changes made to the parameter inside the function have no
effect on the argument.
Call by Reference: This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
Formal and Actual Arguments: Arguments which are mentioned in the function call is
known as the actual argument. Actual arguments can be constant, variables, expressions
etc.
Arguments which are mentioned in the definition of the function is called formal arguments.
Formal arguments are very similar to local variables inside the function. Just like local
variables, formal arguments are destroyed when the function ends.
Things to remember about actual and formal arguments.

• Order, number, and type of the actual arguments in the function call must match
with formal arguments of the function.
• If there is type mismatch between actual and formal arguments then the compiler
will try to convert the type of actual arguments to formal arguments if it is legal,
Otherwise, a garbage value will be passed to the formal argument.
• Changes made in the formal argument do not affect the actual arguments.
Recursion and recursive function: Expressing an entity in terms of itself is called
recursion. Recursion is a programming method in which a function calls itself.
A recursive function is a function that calls on itself. Two important conditions that
must be satisfied by any recursive functions are:
i.Each time a function calls itself and it must be closer to a solution.
ii.There must be decision criteria for stopping the process.
Base case and recursive case of recursive problems: There are two different parts of
recursive problems. The base case- this part does not call itself. It handles a simple
case that we know how to do without breaking the problem down into a simpler
problem.
The recursive case- This part breaks the problem into a simpler version of the original
problem. This part makes(at least) one recursive call to itself.
1. Write a program to create a function float add(int, float);. The task of
this function is to calculate the sum of passed values and return it to the calling
function. Call this function from main() and display the result.
#include<stdio.h>
#include<conio.h>
float add(int , float);
void main()
{
int x;
float y;
int r;
printf(“Enter any two numbers:”);
scanf(“%d%f”,&x,&y);
r=add(x,y);
printf(“Sum = %d”,r);
getch();
}
float add(int a, float b)
{
int sum;
sum=a+b;
return(sum);
}
OUTPUT:
2. Write a program to create a function void sumOfDigits(int); . This function
must calculate the sum of digits in the given number and displays the sum.
#include<stdio.h>
#include<conio.h>
void sumOfDigits(int);
void main(){
int n;
printf(“Enter any digit: “);
scanf(“%d”,&n);
sumOfDigits(n);
getch();
}
void sumOfDigits(int n)
{
int rem,sum=0,temp;
temp=n;
do{
rem=n%10;
sum+=rem;
n=n/10;
}while(n!=0);
printf(“\nThe sum of digits of %d is %d”,temp,sum);
}
OUTPUT:
3. Write a program to read a non-negative integer in main(). Pass this integer
to a function fact() having return type unsigned integer. This function
calculates the factorial of the received number and return to main() to display
it.
#include<stdio.h>
#include<conio.h>
unsigned int fact(int n);
int main()
{
unsigned int n;
long int r;
printf(“Enter any number “);
scanf(“%u”,&n);
r=fact(n);
printf(“The factorial of %u = %ld”,n,r);
getch();
return(0);
}
unsigned int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
OUTPUT:

4. Write a program to create a function void check_prime(); The task of this


function is to read a number and check whether the number is prime or not
and display the appropriate message. Be sure that a real number cannot be
either prime or composite. What about negative numbers?
#include<stdio.h>
#include<conio.h>
void check_prime();
void main()
{
check_prime();
}
void check_prime(){
int i,count=0; float n;
printf(“Enter any number “);
scanf(“%f”,&n);
if(n<=1 || (n-(int)n)!=0)
printf(“Enter a valid number”);
else{
for(i=1;i<=n;i++)
{
if((int)n%i==0)
count++;
}
if(count==2)
printf(“\nThe number %.0f is prime”,n);
else
printf(“\nThe number %.0f is not a prime”,n);
getch();
}
}
OUTPUT:

5. Combine question 1, 2, 3, 4 using switch statement. For this, display a menu


on the screen to prompt the user whether he wants to sum two numbers or sum
of digits of an integer or calculate the factorial of an integer or to know
whether a number is prime or not.
#include<stdio.h>
#include<conio.h>
float add ();
void sumOfDigits ();
unsigned int fact (float);
void check_prime ();

void main ()
{
int n; float n1;
char c;
do
{
printf (“1. Sum of two numbers”);
printf (“\n2. Sum of digits of an integer”);
printf (“\n3. Factorial of an integer”);
printf (“\n4. Prime or Composite”);
printf (“\nEnter your choice (1, 2, 3, 4): “);
scanf (“%d”, &n);
switch(n)
{
case 1:
printf (“Sum=%f”, add ());
break;
case 2:
sumOfDigits ();
break;
case 3:
printf(“Enter a number: “);
scanf(“%f”,&n1);
if(n1>=0 && (n1-(int)n1)==0)
printf(“Factorial of %.0f is %ld”,n1,fact(n1));
else
printf(“Enter a valid number”);
break;
case 4:
check_prime ();
break;
default:
printf (“Enter a number from 1-4”);
break;
}
printf (“\n Enter ‘e’ to exit and any other character to continue”);
scanf (“ %c”, &c);
}
while (c != ‘e’);
getch ();
}
float add ()
{
float a, b, sum;
printf (“Enter any two numbers:”);
scanf (“%f%f”, &a, &b);
sum = a + b;
return sum;
}

void sumOfDigits ()
{
int rem, sum = 0, temp, n;
printf (“Enter any digit: “);
scanf (“%d”, &n);
temp = n;
do
{
rem = n % 10;
sum += rem;
n = n / 10;
}
while (n != 0);
printf (“\nThe sum of digits of %d is %d”, temp, sum);
}

unsigned int fact (float nm)


{
if(nm==0)
return 1;
else
return(nm*fact(nm-1));
}
void check_prime ()
{
int i, count = 0;
float n;
printf (“Enter any number “);
scanf (“%f”, &n);
if (n <= 1 || (n – (int) n) != 0)
printf (“Enter a valid number”);
else
{
for (i = 1; i <= n; i++)
{
if ((int) n % i == 0)
count++;
}
if (count == 2)
printf (“\nThe number %.0f is prime”, n);
else
printf (“\nThe number %.0f is not a prime”, n);
}
}
OUTPUT:

6. Write a program to read an unsigned integer in main() pass it to a function


(void countsDigits(int*, int*). This function counts number of odd digits and
even digits in it. Display the counts from main. Use concept of passing
arguments by reference.
#include<stdio.h>
#include<conio.h>
unsigned int n;
void countsDigits(int*,int*);
void main(){
int odd_count=0,even_count=0;
printf(“Enter an integer number: “);
scanf(“%u”,&n);
countsDigits(&odd_count,&even_count);
printf(“\nNumber of odd numbers = %d”,odd_count);
printf(“\nNumber of even numbers = %d”,even_count);
}
void countsDigits(int *oc, int *ec)
{
int rem;
while(n!=0)
{
rem=n%10;
if(rem%2==0)
*ec=*ec+1;
else
*oc=*oc+1;
n=n/10;
}
}
OUTPUT:

7. Write a program to create functions: int findLowest(int, int, int); and int
findHighest(int, int, int);. The task of findLowest() is to find the lowest of three
integers and return an integer to the calling function. Similarly, the task of
findHighest() is to find the highest of three integers and return an integer to
the calling function. Call these functions in main() giving appropriate
arguments. (Note: Use conditional operator (test
expression?expression1:expression2) to find highest and lowest number.
#include<stdio.h>
#include<conio.h>
int findLowest(int,int,int);
int findHighest(int,int,int);
void main(){
int a,b,c;
printf(“Enter three integer numbers: “);
scanf(“%d%d%d”,&a,&b,&c);
printf(“\nThe lowest number is %d”,findLowest(a,b,c));
printf(“\nThe greatest number is %d”,findHighest(a,b,c));
getch();
}
int findLowest(int a,int b,int c)
{
int Low;
Low=(a<b&&a<c?a:b<c?b:c);
return Low;
}
int findHighest(int a,int b,int c)
{
int High;
High=(a>b&&a>c?a:b>c?b:c);
return High;
}
OUTPUT:

8. Write separate programs using recursive function to compute n!, x , HCF of


n

two numbers, sum from 1 to n. Declare variables of appropriate types and read
from the user. Also, check the read values from the users are also suitable for
computing or not.
#include<stdio.h>
#include<conio.h>
long int factorial(int);
void main()
{
float n;
printf(“Enter a number: “);
scanf(“%f”,&n);
if(n>=0 && (n-(int)n)==0)
printf(“Factorial of %.0f is %ld”,n,factorial(n));
else
printf(“Enter a valid number”);
}
long int factorial(int n)
{
if(n==0)
return 1;
else
return(n*factorial(n-1));
}
OUTPUT:

#include<stdio.h>
#include<conio.h>
int power(float x, float n);
int main()
{
float x,n;
printf(“Enter the value of x and n “);
scanf(“%f%f”,&x,&n);
if((x>=0 && (x-(int)x)==0) && (n>=0 && (n-(int)n)==0))
printf(“%.0f to the power %.0f = %d”,x,n,power(x,n));
else
printf(“Enter a valid number”);
}
int power(float x,float n)
{
if(n==0)
return(1);
else
return(x*power(x,n-1));
}
OUTPUT:

#include<stdio.h>
#include<conio.h>
int gdchcf(int, int);
void main(){
float a,b;
printf(“Enter two numbers to calculate HCF: “);
scanf(“%f%f”,&a,&b);
if((a>0 && (a-(int)a)==0) && (b>0 && (b-(int)b)==0))
printf(“Greatest common divisor is %d”,gdchcf(a,b));
else
printf(“Enter a valid number”);

}
int gdchcf(int x,int y)
{
if(y!=0)
return gdchcf(y,x%y);
else
return x;
}
OUTPUT:

#include<stdio.h>
#include<conio.h>
int sum(float x);
int main()
{
float x;
printf(“Enter the value of x: “);
scanf(“%f”,&x);
if(x>0 && (x-(int)x)==0)
printf(“The sum from 1 to the %.0f = %d”,x,sum(x));
else
printf(“Enter a valid number”);
return(0);
}
int sum( float x)
{
if(x==1)
return(1);
else
return(x+sum(x-1));
}
OUTPUT:

9. Write a program using recursive function to compute series: 1 -2 +3 -4 ….(-


2 2 2 2

1) n . Here you cannot use pow() function and you should read the value of n
n+1 2

from the user.


#include<stdio.h>
#include<conio.h>
int series(int,int,int,int);
int power(int,int);
int main()
{
int n,sign=-1,i=1,sum=0;
printf(“Enter the number of terms upto which sum is to be calculated: “);
scanf(“%d”,&n);
sum=series(sum,sign,I,n);
printf(“\nThe sum of the series is %d”, sum);
return 0;
}
int series(int sum,int a,int I,int n)
{
int b=2,term;
if(i>n)
return sum;
else{
a*=-1;
term=a*power(I,b);
sum+=term;
i++;
series(sum,a,I,n);
}
}
int power(int a,int b){
if (b==0)
return 1;
else
return a*power(a,b-1);
}
OUTPUT:

10. Write a program to compute the series:


Sin(x)=x-x /3!+x /5!-x /7!+x /9!........ (-1) x /(2n-1)! Where, n=1,2,3,4…
3 5 7 9 n-1 (2n-1)

Write separate recursive functions to calculate x and n! . n

#include<stdio.h>
#include<conio.h>
#include<math.h>
long int fact(int j)
{
if(j==0)
return 1;
else
return(j*fact(j-1));
}
float numerator(float x, int n)
{
if(n==0)
return 1;
else
return(x*numerator(x,n-1));
}
void main(void)
{
int n,i,j,sign,power;
float term,x,sum=0,numerat;
long int denum;
printf(“\nEnter number of terms:”);
scanf(“%d”,&n);
printf(“\nEnter the value of angle in Degree:”);
scanf(“%f”,&x);
x=x*3.14/180; /*to convert degree to radian. If value of x is in radian, it is not required. */
for(i=1;i<=n;i++)
{ sign=pow(-1,i-1);
power=2*i-1;
numerat=numerator(x,power);
denum=fact(power);
printf(“\nfactorial of %d is:%ld”,power,denum);
term=sign*numerat/denum; /*we can use pow(x,power)*/
printf(“\nTerm:%f”,term);
sum=sum+term;
printf(“\n”);
}
printf(“\nSin(%f) = %f”,x,sum);
}
OUTPUT:
LAB 8 : ARRAYS
Background Theory:
• What is an array?
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. A one-dimensional array is like a list whereas two-dimensional
array is like a table.
• Advantages and Disadvantages of array:
Advantages:
i.In an array, accessing an element is very easy by using the index number.
ii.The search process can be applied to an array easily.
iii.2D Array is used to represent matrices.
iv.For any reason a user wishes to store multiple values of similar type then the
Array can be used and utilized efficiently.
Disadvantages:
i.It allows us to enter only fixed number of elements into it. We cannot alter the size
of the array once array is declared.
ii.Inserting and deleting the records from the array would be costly since we add /
delete the elements from the array, we need to manage memory space too.
• Searching element in array To find an element in the array we use for loop, if
statement and equality operator. If the array element is equal to the searching
element then it will be displayed with position and program.
• Sorting element in array Ordering of data either in ascending or descending order
is called sorting element in array.
• Passing array to functions: In C, arrays are automatically passed by reference to
a function. The name of an array stores the beginning address of where the array
data is stored in memory. When we pass array by reference, the function has access
to all the elements stored in array and any change in the function will be reflected
to the calling function. So, we conclude that array can be passed to a function by
passing only the array name and size of array.
Just as in one-dimensional array, when a two-dimensional (or higher
dimensional) array is passed as a parameter, the base address of the actual array is
sent to the function(passed by reference). Any change made to the elements of an
array element inside a function will carry over to the original location of the array
that is passed to the function. The size of all dimensions except the first must be
included in the function heading and prototype. The sizes of those dimensions for
the formal parameter must be exactly the same as in the actual array. The function
header and prototype specify the number of columns as a constant. For example,
the following function declaration are valid:
void function1 (int x[8][5], int cs[]);
int function2 (int x[][5], float m);
int function3 (int [][5], float);

• ONE DIMENSIONAL ARRAYS

1. void main()
{
int i, num[6]={4,5,3,2,15};
for(i=0;i<6;i++)
printf(“%d”,num[i]);
getch();
}
OUTPUT:

2. void main()
{
int i, num[6];
printf(“Enter members of array:”);
for(i=0;i<6;i++)
scanf(“%d”,&num[i]);
for(i=0;i<6;i++)
printf(“%d”,num[i]);

getch();
}
OUTPUT:

3. Write a program to find the sum of elements of an integer array of size 5 that
are divisible by 10 but not by 15.
#include<stdio.h>
#include<conio.h>
void main(){
int num[5],i,sum=0;
for(i=0;i<5;i++){
printf(“Enter number %d “,i+1);
scanf(“%d”,&num[i]);
if(num[i]%10==0 && num[i]%15!=0)
sum=sum+num[i];
}
printf(“\nSum of elements divisible by 10 not by 15 is: %d”,sum);
}
OUTPUT:

4. Write a program to add the elements at corresponding position of two arrays of


size n. Read value of n from the user.
#include <stdio.h>
#include<conio.h>
void main() {
int n, i;
printf(“Enter value of n: ”);
scanf(“%d”, &n);
int numArrayA[n], numArrayB[n], sumArray[n];
for (i=0; i<n; i++) {
printf(“Enter element of array I : “);
scanf(“%d”, &numArrayA[i]);
}
for (i=0; i<n; i++) {
printf(“Enter element of array II : “);
scanf(“%d”, &numArrayB[i]);
}
for(i=0;i<n;i++){
sumArray[i]=numArrayA[i]+numArrayB[i];
}
for (i=0; i<n; i++) {
printf(“\nCoreesponding elements sum = %d”, sumArray[i]);
}
printf(“\n”);
}
OUTPUT:

5. Write a program to find highest and lowest elements of an array of size 5.


#include<stdio.h>
#include<conio.h>
void main(){
float num[5],max,low;
int i;
for(i=0;i<5;i++)
{
printf(“Enter element %d: “,i+1);
scanf(“%f”,&num[i]);
}
max=num[0];
low=num[0];
for(i=0;i<5;i++)
{
if (num[i]>max)
max=num[i];
}
printf(“\n Largest element is %f”,max);
for(i=0;i<5;i++)
{
if (num[i]<low)
low=num[i];
}
printf(“\n Smallest element is %f”,low);
}
OUTPUT:

6. Write a program to read elements of an array in main() pass it to a function to sort it in


ascending/descending order. Display the sorted array from main().
//Arranging elements of the array in ascending order
#include<stdio.h>
#include<conio.h>
void sort(int n, int num[]);
void main()
{
int num[100],i,n;
printf(“Enter the size of an array “);
scanf(“%d”,&n);
printf(“Enter the elements of an array\n”);
for(i=0;i<n;i++){
printf(“num[%d]=”,i+1);
scanf(“%d”,&num[i]);
}
sort(n,num);
printf(“\n Sorted array is:”);
for(i=0;i<n;i++)
printf(“\nnum[%d]=%d”,i+1,num[i]);
}
void sort(int n,int num[])
{
int I,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(num[j]<num[i]) //> descending <ascending
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
}
OUTPUT:

7. Write a program to raise the power of each member by 3.


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
float num[50],c;
int i,n;
printf(“Enter the number of array elements: “);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“ Num[%d] : “,i+1);
scanf(“%f”,&num[i]);
}
printf(“Arrays raised to power 3:”);
for(i=0;i<n;i++){
c=pow(num[i],3);
printf(“\n Num[%d] : %.3f”,i+1,c);
}
}
OUTPUT:

8. Write a program to read an unsigned integer array in main(). Pass it to a function


that counts the Armstrong members and return the count to main().
#include<stdio.h>
#include<conio.h>
int countarms(unsigned int);
void main(){
unsigned int num[30];
int i,n,c,count=0;
printf(“Enter the range of array: “);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“Num[%d] : “,i+1);
scanf(“%u”,&num[i]);
c=countarms(num[i]);
count+=c;
}
printf(“\nNumber of rmstrong numbers is: %d”,count);
}
int countarms(unsigned int num){
int temp,c,r,sum=0;
temp=num;
while (num>0)
{
r=num%10;
c=r*r*r;
sum=sum+c;
num=num/10;
}
num=temp;
if(num==sum)
return 1;
else
return 0;
}
OUTPUT:

9. Write separate programs to compute the median, range, variance and standard
deviation. Note: Variance= (x2)/n-((x)/n) and standard deviation is variance.
2

Median
//Taking 5 items in individual series
#include<stdio.h>
#include<conio.h>
void main()
{
int num[5],i,n=0;
printf(“Enter the elements of an array\n”);
for(i=0;i<5;i++){
printf(“num[%d]=”,i+1);
scanf(“%d”,&num[i]);
n++;
}
printf(“\n Arranging the data in ascending order:”);
int j,temp;
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(num[j]<num[i])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
for(i=0;i<5;i++){
printf(“\nnum[%d]=%d”,i+1,num[i]);
}
printf(“\nMedian is size of %drd item = %d”,((n+1)/2),num[i/2]);
}
OUTPUT:

Range
#include<stdio.h>
#include<conio.h>
void main(){
int num[30],i,n,max,low,range;
printf(“Enter the number of elements: “);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“ Num[%d] = “,i+1);
scanf(“%d”,&num[i]);
}
max=num[0];
low=num[0];
for(i=0;i<n;i++)
{
if (num[i]>max)
max=num[i];
}
printf(“\n Largest element is %d”,max);
for(i=0;i<n;i++)
{
if (num[i]<low)
low=num[i];
}
printf(“\n Smallest element is %d”,low);
range=max-low;
printf(“\n Range of given data is = %d”,range);
}
OUTPUT:

Variance
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
int num[30],i,n,sum=0,sq,sum1;
float t1,t2,var;
printf(“Enter the number of elements: “);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“ Num[%d] = “,i+1);
scanf(“%d”,&num[i]);
sq=pow(num[i],2);
sum1+=sq;
sum+=num[i];
}
t1=(float)sum1/n;
t2=(float)sum/n;
var=t1-t2*t2;
printf(“\nMean is = %.3f”,t2);
printf(“\nVaraince is = %.3f”,var);
}
OUTPUT:

Standard Deviation
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
int num[30],i,n,sum=0,sq,sum1;
float t1,t2,var,sd;
printf(“Enter the number of elements: “);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“ Num[%d] = “,i+1);
scanf(“%d”,&num[i]);
sq=pow(num[i],2);
sum1+=sq;
sum+=num[i];
}
t1=(float)sum1/n;
t2=(float)sum/n;
var=t1-t2*t2;
sd=sqrt(var);
printf(“\nVaraince is = %.3f”,var);
printf(“\nStandard Deviation is = %.3f”,sd);
}
OUTPUT:

10. Write a program to read an array in main() of size 10 and of type float. Pass the array to a function
that finds the highest and lowest member. Display the sum of highest and lowest and difference
between highest and lowest from main() using passing by reference. Display highest and lowest
members from the function and their position in the array as well.
#include<stdio.h>
#include<conio.h>
void High_Low(float num[],float*,float*);
void main(){
float num[10],max,low,sum,diff;
int i;
for(i=0;i<5;i++)
{
printf(“Enter element %d: “,i+1);
scanf(“%f”,&num[i]);
}
High_Low(num,&sum,&diff);
printf(“\nThe sum of highest and lowest is: %.2f”,sum);
printf(“\nThe diff. of highest and lowest is: %.2f”,diff);
}
void High_Low(float num[],float *sum,float *diff)
{
float max,low;int I,temp;
max=num[0];
low=num[0];
for(i=0;i<5;i++)
{
if (num[i]>max){
max=num[i];
temp=i;
}
}
printf(“\n Largest element is %.2f”,max);
if (max!=num[0]){
printf(“\n Position of largest array is %d”,temp);
}
else {
printf(“\n Position of largest array is 0”);
}
for(i=0;i<5;i++)
{
if (num[i]<low){
low=num[i];
temp=i;
}
}
printf(“\n Smallest element is %.2f”,low);
if (low!=num[0]){
printf(“\n Position of smallest array is %d”,temp);
}
else {
printf(“\n Position of smallest array is 0”);
}
*sum=max+low;
*diff=max-low;
}
OUTPUT:
• TWO DIMENSIONAL ARRAYS

1.
void main(){
int i,j,num[2][2]={{4,5},{6,7}};
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf(“%d”,num[i][j]);
getch();
}
OUTPUT:

2.
void main(){
int i,j,num[3][3];
printf(“Enter members of array:”);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&num[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”,num[i][j]);
getch();
}
OUTPUT:

3. Write a program to find the sum of elements of an integer array of size 3x3
that are divisible by 7 but not by 5.
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,num[3][3],sum=0;
printf(“Enter members of array:\n”);
for(i=0;i<3;i++)
for(j=0;j<3;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%d”,&num[i][j]);

if(num[i][j]%7==0 && num[i][j]%5!=0)


sum=sum+num[i][j];
}

printf(“Sum of elements divisible by 7 not by 5 is: %d”,sum);


}
OUTPUT:
4. Write a program to add the elements at corresponding position of two arrays
of size MxN. Read values of M and N from the user.
#include <stdio.h>
#include<conio.h>
void main() {
int i,j,row,col;
int mat1[20][20], mat2[20][20], mat3[20][20];
printf(“Enter value of rows and columns: “);
scanf(“%d%d”, &row,&col);
printf(“Enter first matrix: \n”);
for (i=0; i<row; i++) {
for(j=0;j<col;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%d”, &mat1[i][j]);
}
}
printf(“Enter second matrix: \n”);
for (i=0; i<row; i++) {
for(j=0;j<col;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%d”, &mat2[i][j]);
}
}
for(i=0;i<row;i++){
for(j=0;j<col;j++){
mat3[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf(“\nResultant array: \n”);
for (i=0; i<row; i++) {
for(j=0;j<col;j++){
printf(“%5d”,mat3[i][j]);
}
printf(“\n”);
}
}

OUTPUT:

5. Write a program to find highest and lowest elements of an array of size 3x3.
#include<stdio.h>
#include<conio.h>
void main(){
float num[3][3],max,low;
int i,j;
printf(“Enter elements of array: \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%f”,&num[i][j]);
}
}
max=num[0][0];
low=num[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
if (num[i][j]>max)
max=num[i][j];
}
}
printf(“\n Largest element is %.3f”,max);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
if (num[i][j]<low)
low=num[i][j];
}
}
printf(“\n Smallest element is %.3f”,low);
}
OUTPUT:
6. Write a program to read members of 3x3 array in main(). Pass the array to a
function that finds the sum of diagonal elements and returns to main(). Display
the returned values.
#include<stdio.h>
#include<conio.h>
float diagonal(float num[3][3]);
void main(){
float num[3][3],max,low;
int i,j;
printf(“Enter elements of array: \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%f”,&num[i][j]);
}
}
printf(“The matrix form is: \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
printf(“%.2f\t”,num[i][j]);
}
printf(“\n”);
}
printf(“\nThe sum of diagonal elements is: %.2f”,diagonal(num));
}
float diagonal(float num[3][3]){
float sum=0;int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
if(i==j)
sum+=num[i][j];

}
}
return sum;
}
OUTPUT:
7. Write a program to raise the power of each member by 5.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
float num[50][50],c;
int i,j,n;
printf(“Enter the number of array elements: “);
scanf(“%d”,&n);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf(“ Num[%d][%d] : “,i+1,j+1);
scanf(“%f”,&num[i][j]);
}
}
printf(“Arrays raised to power 3:”);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
c=pow(num[i][j],5);
printf(“\n Num[%d][%d] : %.3f”,i+1,j+1,c);
}
}
}
OUTPUT:
8. Write a program to generate a matrix of size 4*4 whose elements are given
by the expression a =3 .
ij
-(i+j)

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
float mat[4][4],c;
int i,j;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
printf(“ Num[%d][%d] : “,i+1,j+1);
scanf(“%f”,&mat[i][j]);
}
}
printf(“The required matrix is :\n”);
for(i=0;i<4;i++){
for(j=0;j<4;j++){
c=pow(3,(-((i+1)+(j+1))));
printf(“%.3f\t”,c);
}
printf(“\n”);
}
}
OUTPUT:
9. Write a program to find the sum of individual rows of a two-dimensional array
and assign them to a one-dimensional array and display the content of one-
dimensional array.
#include<stdio.h>
#include<conio.h>
int a,b;
void row_sum(float num[15][15]);
void main(){
float num[15][15];
int i,j;
printf(“Enter the size of 2D array: \n”);
scanf(“%d%d”,&a,&b);
printf(“Enter elements of array: \n”);
for(i=0;i<a;i++)
{
for(j=0;j<b;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%f”,&num[i][j]);
}
}
printf(“The matrix form is: \n”);
for(i=0;i<a;i++)
{
for(j=0;j<b;j++){
printf(“%.2f\t”,num[i][j]);
}
printf(“\n”);
}
printf(“The sum of row elements in 1D is:\n”);
row_sum(num);
}
void row_sum(float num[15][15]){
int i,j;
for(i=0;i<a;i++)
{
float sum=0;
for(j=0;j<b;j++){
sum+=num[i][j];
}
printf(“%.2f\t”,sum);
}
}
OUTPUT:

10. Write a program that reads two matrices of order mxn and pxq using function readMatrix().
The program should contain a function processMatrix() that takes the matrices and multiplies
them. The result of multiplication must be displayed using a function showMatrix(). Read the
values of m, n, p and q from the keyboard.
#include<stdio.h>
#include<conio.h>
void readMatrix(int num1[20][20],int num2[20][20],int,int,int,int);
void processMatrix(int num1[20][20],int num2[20][20],int sum[20][20],int,int,int);
void showMatrix(int sum[20][20],int,int);
int main(){
int num1[20][20],num2[20][20],sum[20][20],m,n,p,q;
printf(“Enter the order of first matrix: “);
scanf(“%d%d”,&m,&n);
printf(“Enter the order of second matrix: “);
scanf(“%d%d”,&p,&q);
if(n==p){
readMatrix(num1,num2,m,n,p,q);
processMatrix(num1,num2,sum,m,p,q);
showMatrix(sum,m,q);
}
else
printf(“Invalid order of matrix ! \n Try Again !”);
return 0;
}
void readMatrix(int num1[20][20],int num2[20][20],int m,int n,int p,int q){
printf(“Enter elements of first matrix: \n”);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%d”,&num1[i][j]);
}
}
printf(“Enter elements of second matrix: \n”);
for(int i=0;i<p;i++){
for(int j=0;j<q;j++){
printf(“Num [%d][%d] = “,i+1,j+1);
scanf(“%d”,&num2[i][j]);
}
}
}
void processMatrix(int num1[20][20],int num2[20][20],int sum[20][20],int m,int p,int q){

printf(“\nThe multiplicated matrix is :\n”);


for(int i=0;i<m;i++){
for(int j=0;j<q;j++){
sum[i][j]=0;
for(int k=0;k<p;k++){
sum[i][j]+=num1[i][k]*num2[k][j];
}
}
}
}
void showMatrix(int sum[20][20],int m,int q){
for(int i=0;i<m;i++){
for(int j=0;j<q;j++)
printf(“%d\t”,sum[i][j]);
printf(“\n”);
}

}
OUTPUT:
• Analysis and Discussion:
In Lab 7, we dealt with a different approach to solve the
programming problems than previous labs. We introduced to new topic Functions and
used various user defined functions by passing various arguments and returning value.
We concluded that there must be one function to run C program which is main() by
default and we can define other function name as our choice to break up program into
simpler parts for our simplicity.
In Lab 8 also, we introduced with a new concept of using array(one-
dimensional and two-dimensional) in programs to store the similar type of data items
in contiguous memory locations. Use of array makes easier to store multiple data items
using a single variable instead of making different variables which ultimately makes
program efficient and saves time. Through 1D array data can be stored in either rows
or columns whereas through 2D array data items can be stored in 2D form (matrix
form) in the form of rows and columns. We, too defined different functions to solve
array problems.
Lab No.: 9 & 10
Title: Pointers & Dynamic Memory Allocation and
Strings

LAB 9 : POINTERS & DYNAMIC MEMORY ALLOCATION


• What is pointer? Why is it useful?
A pointer is a variable whose value is the address of another variable, i.e.,
direct address of the memory location. Like any variable or constant, you must declare
a pointer before using it to store any variable address. The general form of a pointer
variable declaration is −type *var-name;
Uses of pointer:
i.Pointers reduce the length and complexity of a program.
ii.They increase execution speed.
iii.A pointer enables us to access a variable that is defined outside the function.
iv. Pointers are more efficient in handling the data tables.
i.The use of a pointer array of character strings results in saving of data storage space in
memory.
Pointer initialization: Once a pointer variable has been declared, it can be made to
point to a variable using an assignment statement such as
int marl;
int *marks_ptr;
marks_ptr=&marks;
Here, marks_ptr is a pointer variable that points the ordinary variable marks. Before
using pointer variables, they should be initialized. When a pointer initialization takes
place, we are always assigning the reference value to where the pointer points, never
the value being pointed.
Pointer expressions: Like ordinary variables, pointer variables can be used in
expressions. For example, if x1 and x2 are properly declared and initialized pointers,
they can be used in the expressions in the following forms:
p=*x1* *x2;
sum=sum+*x2;
*x1=*x1+40;
x=10*-*x1/x2 same as (10*(-(*x1)))/(*x2)
Dynamic Memory Allocation: Dynamic memory allocation is the process of
allocating memory storage for use in a computer program during the runtime of that
program. It is a way of distributing ownership of limited memory resources among
many pieces of data and code. A dynamically allocated object remains allocated until it
is deallocated explicitly, either by the programmer or by garbage collector.
Malloc(): A block of contiguous memory can be allocated. Using the function malloc,
the malloc function reserves a block of memory of specified size and return a pointer
of type void. This means that it can be casted to any type of pointer. Its general form is:
ptr=(cast-type*)malloc(byte-size); (where ptr is a pointer of cast type)
Calloc(): This function is normally used for allocating memory space at runtime for
storing derived data type, such as array and structures. While malloc allocates single
block of memory, but calloc allocates multiple blocks of memory each of the same size
and sets all bytes to zero. Like malloc, it also returns void pointer on successful
allocation of requested memory area. The void pointer must be casted to point to a
particular type. Its general form is:
ptr=(cast-type*)calloc(n, sizeof(data type of elements));
Realloc(): This functions helps to change the memory size already allocated. This
process is called reallocation of memory. Reallocation of space is done by the
statement:
ptr=realloc(ptr, newsize);
This statement allocated a new memory space of size newsize to the pointer variable
ptr and returns a pointer to the first byte of the new memory block. The newsize may
be larger or smaller than the size. The new memory block may or may not begin at the
same place as the old one. The function guarantees that the old data will remain intact.
Free(): The free function causes the space pointed by ptr to be deallocated, that is,
made available for further allocation. To use free function we do:
free(ptr); where ptr is a pointer to a memory block which has
already been created by malloc or calloc. Use of invalid pointer in the call may create
problems.
1. Run the following programs, observe the output and comment on that.
#include<stdio.h>
void main(){
int a,b;
printf("address of a:%u",&a);
printf("address of b:%u",&b);
getch();
}
OUTPUT:

#include<stdio.h>
void main(){
int *p,*q;/*Declaration of pointer variables*/
int a,b; /*Declaration of ordinary variables*/
p=&a; /*Using referencing operator to initialize pointer variable p.*/
q=&b;
printf("Address of a:%u\n",&a);
printf("Address of b:%u\n",&b);
printf("value of p=%u\n",p);
printf("value of q=%u\n",q);
printf("Enter value of a and b: ");
scanf("%d%d",&a,&b);
printf("The value pointed by p is %d\n",*p); /*Using deferencing operator
(*).*/
printf("The value pointed by q is %d\n",*q);
printf("a+b=%d\n",a+b);
printf("*p+*q=%d",*p+*q); /* *p+*q=pointer expression */
}
OUTPUT:

2. Write a program to find the larger of two numbers using the concept of
function and pointer. Here pass two numbers from main() to a function that
finds the larger. Display the larger one from the main() without using return
statement.
#include<stdio.h>
#include<conio.h>
void larger(int*,int*,int*);
void main(){
int x,y,large;
printf("Enter the values of a and b: ");
scanf("%d%d",&x,&y);
larger(&x,&y,&large);
printf("Larger number is %d",large);
}
void larger(int *x,int *y,int *l){
if(*x>*y)
*l=*x;
else
*l=*y;
}
OUTPUT:

3. Run the following program, observe the output and comment on that.
#include<stdio.h>
void main(){
float marks[5];
int i;
printf("%d",marks);
printf("address of different array elements:");
for(i=0;i<5;i++)
printf("address of element %d is %u\n",i,&marks[i]);
/*printf("address of element %d is %u\n",i,(marks+i)); */
getch();
}
OUTPUT:

There is no any difference in output between using expressions &array[i] and


(array+i) because the latter is other way of accessing array elements with the help of
pointers.

4. This program asks the required size of array to the user and displays the
addresses of allocated blocks.
#include<stdio.h>
#include<stdlib.h>/*header file for memory management functions */
void main(void){
int n,i;
float *address; /*pointer variable declaration */
printf("Enter number of elements:");
scanf("%d",&n);
address=(float*)calloc(n,sizeof(float));
/*using calloc function to allocate memory for n number of float member */
if(address==NULL) /*to check whether the requested memory allocated or not */
{
printf("Memory can not allocated.");
exit(0); /*to exit from the program, if the contents of address is NULL */
}
for(i=0;i<n;i++)
{
printf("\nAddress of %d block %d ",i,(address+i));
}
free(address); /*to deallocate memory */
}
OUTPUT:

5. Solve all the problems of one-dimensional array of exercise eight using the
concept of dynamic memory allocation. Use equivalent notation of pointers and
arrays, for example, as in the following table.
Equivalent expressions of arrays and pointers

i. #include<stdio.h>
#include<stdlib.h>
int main()
{
int i,*num;
num=(int *)malloc(5*sizeof(int));
if(num==NULL){
printf("Memory cannot be allocated");
exit(0);
}
*(num+0)=4;
*(num+1)=5;
*(num+2)=3;
*(num+3)=2;
*(num+4)=15;
for(i=0;i<5;i++)
printf("%d",num[i]);
}
OUTPUT:
ii. #include<stdio.h>
#include<stdlib.h>
int main(){
int i,*ptr;
ptr=(int *)malloc(6*sizeof(int));
if (ptr==NULL){
printf("Memory can't be allocated");
exit(0);
}
printf("Enter members of array: ");
for(i=0;i<6;i++){
scanf("%d",(ptr+i));
}
for(i=0;i<6;i++){
printf("%d",*(ptr+i));
}
free(ptr);
return 0;
}
OUTPUT:

3. Write a program to find the sum of elements of an integer array of size 5 that
are divisible by 10 but not by 15.
#include<stdio.h>
#include<stdlib.h>
void main(){
int i,*num,sum=0;
num=calloc(5,sizeof(int));
if (num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<5;i++){
printf("Enter number %d ",i+1);
scanf("%d",(num+i));
if(*(num+i)%10==0 && *(num+i)%15!=0)
sum=sum+*(num+i);
}
printf("\nSum of elements divisible by 10 not by 15 is: %d",sum);
}
OUTPUT:

4. Write a program to add the elements at corresponding position of two arrays of


size n. Read value of n from the user.
#include <stdio.h>
#include<stdlib.h>
void main() {
int n, *arr1,*arr2,*sumar,i;
printf("Enter value of n: ");
scanf("%d", &n);
arr1=(int*)calloc(n,sizeof(int));
arr2=(int*)calloc(n,sizeof(int));
sumar=(int*)calloc(n,sizeof(int));
if (arr1==NULL && arr2==NULL && sumar==NULL){
printf("Memory can't be allocated");
exit(0);
}
for (i=0; i<n; i++) {
printf("Enter element of array I : ");
scanf("%d",(arr1+i));
}
for (i=0; i<n; i++) {
printf("Enter element of array II : ");
scanf("%d",(arr2+i));
}
for(i=0;i<n;i++){
*(sumar+i)=*(arr1+i)+*(arr2+i);
}
for (i=0; i<n; i++) {
printf("\nCoreesponding elements sum = %d",*(sumar+i));
}
printf("\n");
}
OUTPUT:

5. Write a program to find highest and lowest elements of an array of size 5.


#include<stdio.h>
#include<stdlib.h>
void main(){
float *num,max,low;int i;
num=(float*)calloc(5,sizeof(float));
if (num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<5;i++)
{
printf("Enter element %d: ",i+1);
scanf("%f",(num+i));
}
max=*(num+0);
low=*(num+0);
for(i=0;i<5;i++)
{
if (*(num+i)>max)
max=*(num+i);
}
printf("\n Largest element is %f",max);
for(i=0;i<5;i++)
{
if (*(num+i)<low)
low=*(num+i);
}
printf("\n Smallest element is %f",low);
free(num);
}
OUTPUT:

6. Write a program to read elements of an array in main() pass it to a function to sort it


in ascending/descending order. Display the sorted array from main().
//Arranging elements of the array in ascending order
#include<stdio.h>
#include<stdlib.h>
void sort(int n, int *num);
void main()
{
int *num,i,n;
printf("Enter the size of an array ");
scanf("%d",&n);
num=(int *)calloc(n,sizeof(int));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
printf("Enter the elements of an array\n");
for(i=0;i<n;i++){
printf("num[%d]=",i+1);
scanf("%d",(num+i));
}
sort(n,num);
printf("\n Sorted array is:");
for(i=0;i<n;i++)
printf("\nnum[%d]=%d",i+1,*(num+i));
free(num);
}
void sort(int n,int *num)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(*(num+j)<*(num+i)) //> descending <ascending
{
temp=*(num+i);
*(num+i)=*(num+j);
*(num+j)=temp;
}
}
}
}
OUTPUT:
7. Write a program to raise the power of each member by 3.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main(){
float *num,c;
int i,n;
printf("Enter the number of array elements: ");
scanf("%d",&n);
num=(float *)calloc(n,sizeof(float));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<n;i++){
printf(" Num[%d] : ",i+1);
scanf("%f",(num+i));
}
printf("Arrays raised to power 3:");
for(i=0;i<n;i++){
c=pow(*(num+i),3);
printf("\n Num[%d] : %.3f",i+1,c);
}
free(num);
}
OUTPUT:
8. Write a program to read an unsigned integer array in main(). Pass it to a
function that counts the Armstrong members and return the count to main().
#include<stdio.h>
#include<stdlib.h>
int countarms(unsigned int);
void main(){
unsigned int *num;
int i,n,c,count=0;
printf("Enter the range of array: ");
scanf("%d",&n);
num=(int *)calloc(n,sizeof(int));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<n;i++){
printf("Num[%d] : ",i+1);
scanf("%u",(num+i));
c=countarms(*(num+i));
count+=c;
}
printf("\nNumber of armstrong numbers is: %d",count);
free(num);
}
int countarms(unsigned int num){
int temp,c,r,sum=0;
temp=num;
while (num>0)
{
r=num%10;
c=r*r*r;
sum=sum+c;
num=num/10;
}
num=temp;
if(num==sum)
return 1;
else
return 0;
}
OUTPUT:
9. Write separate programs to compute the median, range, variance and standard
deviation. Note: Variance= (x2)/n-((x)/n) and standard deviation is variance.
2

Median
//Taking 5 items in individual series
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *num,i,n=0;
num=(int *)calloc(5,sizeof(int));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
printf("Enter the elements of an array\n");
for(i=0;i<5;i++){
printf("num[%d]=",i+1);
scanf("%d",num+i);
n++;
}
printf("\n Arranging the data in ascending order:");
int j,temp;
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(*(num+j)<*(num+i))
{
temp=*(num+i);
*(num+i)=*(num+j);
*(num+j)=temp;
}
}
}
for(i=0;i<5;i++){
printf("\nnum[%d]=%d",i+1,*(num+i));
}
printf("\nMedian is size of %drd item = %d",((n+1)/2),*(num+(i/2)));
free(num);
}
OUTPUT:
Range
#include<stdio.h>
#include<stdlib.h>
void main(){
int *num,i,n,max,low,range;
printf("Enter the number of elements: ");
scanf("%d",&n);
num=(int *)calloc(n,sizeof(int));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<n;i++){
printf(" Num[%d] = ",i+1);
scanf("%d",(num+i));
}
max=*(num+0);
low=*(num+0);
for(i=0;i<n;i++)
{
if (*(num+i)>max)
max=*(num+i);
}
printf("\n Largest element is %d",max);
for(i=0;i<n;i++)
{
if (*(num+i)<low)
low=*(num+i);
}
printf("\n Smallest element is %d",low);
range=max-low;
printf("\n Range of given data is = %d",range);
free(num);
}
OUTPUT:
Variance
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main(){
int *num,i,n,sum=0,sq,sum1;
float t1,t2,var;
printf("Enter the number of elements: ");
scanf("%d",&n);
num=(int *)calloc(n,sizeof(int));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<n;i++){
printf(" Num[%d] = ",i+1);
scanf("%d",num+i);
sq=pow(*(num+i),2);
sum1+=sq;
sum+=*(num+i);
}
t1=(float)sum1/n;
t2=(float)sum/n;
var=t1-t2*t2;
printf("\nMean is = %.3f",t2);
printf("\nVaraince is = %.3f",var);
free(num);
}
OUTPUT:
Standard Deviation
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main(){
int *num,i,n,sum=0,sq,sum1;
float t1,t2,var,sd;
printf("Enter the number of elements: ");
scanf("%d",&n);
num=(int *)calloc(n,sizeof(int));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<n;i++){
printf(" Num[%d] = ",i+1);
scanf("%d",num+i);
sq=pow(*(num+i),2);
sum1+=sq;
sum+=*(num+i);
}
t1=(float)sum1/n;
t2=(float)sum/n;
var=t1-t2*t2;
sd=sqrt(var);
printf("\nVaraince is = %.3f",var);
printf("\nStandard Deviation is = %.3f",sd);
free(num);
}
OUTPUT:
10. Write a program to read an array in main() of size 10 and of type float. Pass
the array to a function that finds the highest and lowest member. Display the sum
of highest and lowest and difference between highest and lowest from main()
using passing by reference. Display highest and lowest members from the
function and their position in the array as well.
#include<stdio.h>
#include<stdlib.h>
void High_Low(float *num,float*,float*);
void main(){
float *num,max,low,sum,diff;
int i;
num=(float *)calloc(5,sizeof(float));
if(num==NULL){
printf("Memory can't be allocated");
exit(0);
}
for(i=0;i<5;i++)
{
printf("Enter element %d: ",i+1);
scanf("%f",num+i);
}
High_Low(num,&sum,&diff);
printf("\nThe sum of highest and lowest is: %.2f",sum);
printf("\nThe diff. of highest and lowest is: %.2f",diff);
free(num);
}
void High_Low(float *num,float *sum,float *diff)
{
float max,low;int i,temp;
max=*(num+0);
low=*(num+0);
for(i=0;i<5;i++)
{
if (*(num+i)>max){
max=*(num+i);
temp=i;
}
}
printf("\n Largest element is %.2f",max);
if (max!=*(num+0)){
printf("\n Position of largest array is %d",temp);
}
else {
printf("\n Position of largest array is 0");
}
for(i=0;i<5;i++)
{
if (*(num+i)<low){
low=*(num+i);
temp=i;
}
}
printf("\n Smallest element is %.2f",low);
if (low!=*(num+0)){
printf("\n Position of smallest array is %d",temp);
}
else {
printf("\n Position of smallest array is 0");
}
*sum=max+low;
*diff=max-low;
}
OUTPUT:

LAB 10 : STRING
• Introduction to String:
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by
a null.
• Roll of null character at the end of strings:
A null character is a character with all its bits set to zero. Therefore, it has a numeric
value of zero and can be used to represent the end of a string of characters, such as a
word or phrase. This helps programmers determine the length of strings.
• Some string handling functions:
• strlen(): This function finds the length of the string. To find the length of
string, it counts and returns the number of characters in the string without
including the null character. The general form is:
l=strlen(string);
where l is the integer variable which receives the value of the length of the
string.
string is an argument given to find the length. Which may be a constant
string also.
• strcat(): This concatenates(joins) two strings together. Its general form is:
strcat(string1,string2);
string1 and string2 are character arrays. Which are given as argument to the
function. When strcat is executed, string2 is appended to string1. It does so
by removing the null character at the end of string1and placing string2 from
there. The string2 remains unchanged.
• strcpy(): This function copies one string to another. It takes the form:
strcpy(deststring,sourcestring);
deststring and sourcestring are two strings as argument to the function.
Which may be character array or string constant. When this function is
executed, it will assign the content of string variable sourcestring to the
string variable deststring.
• strcmp(): The strcmp function compares two strings. The general form of the
string is:
strcmp(string1,string2);
where string1 and string2 are arguments, which may be character arrays or
string constants. When this function is executed it returns 0 if both strings are
equal. If the strings are not equal, it returns the numeric difference between
first mismatching characters in the strings.

1. Run the following program, observe the output and comment on it.
#include<stdio.h>
#include<string.h>
void main(){
int i;
char name1[]="pokhara city";
char name2[]={'k','a','t','h','m','a','n','d','u','c','i','t','y','\0'};
for(i=0;i<strlen(name1);i++)
printf("%c\n",name1[i]);
for(i=0;i<strlen(name2);i++)
printf("%c\t",name2[i]);
getch();
}
OUTPUT:

2. Write a program to check whether a string given by the user is Palindrome or


not.
#include<stdio.h>
#include<string.h>
void main(void){
char astring[100];
int i,length,j,flag=1;
printf("Enter a string:");
scanf("%[^\n]",astring);
length=strlen(astring);
for(i=0,j=length;i<length/2;i++,j--)
{
if(astring[i]!=astring[j-1])
{
flag=0;
break;
}
}
if(flag==1)
printf("\n%s is a palindrome string",astring);
else
printf("\n%s is not a palindrome string",astring);
}
OUTPUT:

3. Write a program to read a string in main(), pass it to a function that returns the
count the number of words to main(). Display the count.
#include<stdio.h>
#include<string.h>
int wordcount(char str[]);
int main(){
char str[100];
printf("Enter a string: ");
scanf("%[^\n]s",str);
printf("\nNumber of words in given string is: %d",wordcount(str));
return 0;
}
int wordcount(char str[]){
int count=1;
for (int i=0;str[i] !='\0';i++)
{
if (str[i]==' ')
count++;
}
return count;
}
OUTPUT:

4. Write a program to read a string in main() using gets(). Pass it to a function


that finds the longest word of the string, counts the number of vowels and
consonants in the word and display the counts and the word from main().
#include<stdio.h>
#include<string.h>
int wordcount(char str[]);
int main(){
char str[100];int j;char word[50];
printf("Enter a string: ");
gets(str);
wordcount(str);

return 0;
}
int wordcount(char str[]){
char tempword[50],word[50];int i=0,v,length=0,count=0,vowcount=0,concount=0;
while(str[i]!='\0'){
if(str[i]==' '){
tempword[count]='\0';
if(length<count){
length=count;
strcpy(word,tempword);
}
count=0;
}
else{
tempword[count]=str[i];
count++;
}
i++;
}
printf("\nThe longest word of given string is: %s",word);
count=1;
for (int i=0;word[i] !='\0';i++)
{
if (word[i]=='A' || word[i]=='E' || word[i]=='I' || word[i]=='O' || word[i]=='U' || word[i]=='a' ||
word[i]=='e' || word[i]=='i' || word[i]=='o' || word[i]=='u')
vowcount++;
else
concount++;
}
printf("\nVowel letters count is: %d",vowcount);
printf("\nConsonant letters count is: %d",concount);
return 0;
}
OUTPUT:

5. Write a program to reverse a word using recursive function.


# include <stdio.h>
#include<conio.h>
void reverse(char *str)
{
if (*str)
{
reverse(str+1);
printf("%c", *str);
}
}
int main()
{
char a[100];
printf("Enter a string: ");
gets(a);
reverse(a);
return 0;
}
OUTPUT:

6. Write separate programs that exactly simulate the task strlen(), strcat(), strcpy()
and strcmp() using user defined functions.
• Program simulating strlen():
#include<stdio.h>
#include<conio.h>
int udrstrlen(char []);
void main(){
char text1[205];
int length;
printf("Enter a string: ");
gets(text1);
length=udrstrlen(text1);
printf("Length of given string is: %d",length);
getch();
}
int udrstrlen(char txt1[])
{
int len;
for(len=0;txt1[len]!='\0';len++);
return len;
}
• Program simulating strcat():
#include<stdio.h>
#include<conio.h>
void udstrcat(char [],char []);
void main(void){
char text1[205];
char text2[100];
printf("Enter a string1: ");
gets(text1);
printf("Enter a string2: ");
gets(text2);
udstrcat(text1,text2);
puts(text1);
}
void udstrcat(char txt1[],char txt2[])
{
int i,j;
for(i=0;txt1[i]!='\0';i++);
for(j=0;txt2[j]!='\0';i++,j++){
txt1[i]=txt2[j];
}
txt1[i]='\0';
printf("Concatenated string is: ");
}

• Program simulating strcpy():


#include<stdio.h>
#include<conio.h>
void udstrcpy(char [],char []);
void main(){
char text1[50];
char text2[50];
printf("Enter a string1: ");
gets(text1);
printf("Enter a string2: ");
gets(text2);
udstrcpy(text1,text2);
printf("%s",text1);

}
void udstrcpy(char txt1[],char txt2[])
{
int i;
i=0;
while(txt2[i]!='\0'){
txt1[i]=txt2[i];
i++;
}
txt1[i]='\0';
printf("Copied string is: \n");
}

• Program simulating strcmp():


#include<stdio.h>
#include<conio.h>
int udstrcmp(char [],char []);
void main(){
char text1[50];
char text2[50];
int diff;
printf("Enter first string: ");
gets(text1);
printf("Enter second string: ");
gets(text2);
diff=udstrcmp(text1,text2);
if(diff==0)
printf("\nDifference is %d. So, strings are equal.",diff);
else
printf("\nDifference is %d. So, strings are unequal.",diff);

}
int udstrcmp(char txt1[],char txt2[])
{
int i=0,d;
do{
d=txt1[i]-txt2[i];
if(d!=0)
break;
i++;
}while(txt1[i]!='\0' || txt2[i]!='\0');
return d;
}

7. Write a program that will read a string and rewrite it in the alphabetical
order. For example, the word NEPAL should be written as AELNP.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[100];
printf("\n Enter the string : ");
scanf("%s",string);
char temp;
int i, j;
int n = strlen(string);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (string[i] > string[j]) {
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
printf("The sorted string is : %s",string);
return 0;
}
OUTPUT:

8. Write a program to find the frequency of a character in the string entered by


a user.
#include<stdio.h>
#include<string.h>
void main(void){
char astring[100],ch;
int i=0,charactercount=0;
printf("%c",ch);
printf("Enter a string: ");
gets(astring);
printf("Enter a character to find check its frequency: ");
scanf("%c",&ch);
do{
if(astring[i]==ch)
charactercount++;
i++;
} while(astring[i]!='\0');
printf("\nThe number of %c is %d",ch,charactercount);
}
OUTPUT:
9. Write a program to count the frequency of characters in the string entered by a
user.
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,j,k,count=0,n;
printf("Enter the string : ");
gets(s);
for(j=0;s[j];j++);
n=j;
printf(" frequency count character in string:\n");
for(i=0;i<n;i++)
{
count=1;
if(s[i])
{
for(j=i+1;j<n;j++)
{
if(s[i]==s[j])
{
count++;
s[j]='\0';
}
}
printf(" '%c' = %d \n",s[i],count);
}
}
return 0;
}
OUTPUT:

10. Write a program to read a string in main(). Pass it to a function. The


function converts all the uppercase characters to lowercase and vice versa.
#include<stdio.h>
#include<conio.h>
void stringconvert(char []);
void main(){
char string[100];
printf("Enter a string: ");
gets(string);
printf("String before conversion: ");
puts(string);
stringconvert(string);
printf("\nString after conversion: ");
puts(string);
}
void stringconvert(char str[]){
int i=0;
while(str[i]!='\0')
{
if(str[i]>='a'&&str[i]<='z')
str[i]=str[i]-32;
else if(str[i]>='A'&&str[i]<='Z')
str[i]=str[i]+32;
i++;
}
}
OUTPUT:

11. Write a program to read name of 10 students in main(). Pass the name list
to a function that sorts the array in ascending order. Display the sorted array
from main().
#include<stdio.h>
#include<conio.h>
#include<string.h>
void sortarray(char [][50]);
void main()
{
char str[10][50];
int i, j;
printf("\nEnter names:\n");
for(i=0;i<10;i++){
printf("%d. ",i+1);
gets(str[i]);
}
printf("\n Sorted strings: \n");
sortarray(str);
for(i=0;i<10;i++){
printf("%d. ",i+1);
puts(str[i]);
}
}
void sortarray(char str[10][50]) {
char temp[50];
for(int i=0;i<10;i++)
{
for(int j=0;j<9;j++)
{
if(strcmp(str[j],str[j+1])>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
}
OUTPUT:
11. Write a program to do the following:
• To print the question “Who is the prime minister of Nepal?”
• To accept the answer.
• To print “Good” and stop if the answer is correct.
• To print the message “try again”, if the answer is wrong.
• To display the correct answer when the answer is wrong even at the third
attempt and stop.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(){
char ans[100];int c,i=0;
char ans1[]="Sher Bahadur Deuba";
here:
printf("\nWho is the prime minister of Nepal?\n");
gets(ans);
c=strcmp(ans,ans1);
if(c!=0){
if(i<2){
printf("Try Again !!!");
}
i++;
if(i<=2)
goto here;
else if(i==3)
printf("\nThe correct answer is: %s",ans1);
}
else if(c==0)
printf("Good");
return 0;
}
OUTPUT:
• Analysis and Discussion:
We began Lab 9 with the concept of pointer. Similar questions as in
1D array were accomplished in this lab using pointer and dynamic memory allocation.
The main purpose of using pointers is to save memory space and achieve faster
execution time whereas dynamic memory allocation is used for allocating the memory
space during the runtime of the program. For that, different functions viz-malloc(),
calloc(), realloc() and free() functions were used.
In Lab 10 we dealt with the problems of strings. We learnt the use
of various string handling functions viz- strlen(), strcat(), strcpy(), strcmp() and so on
their implementation as well. We must include files using #include<string.h> while
using these functions in our program.

Lab No.: 11 & 12


Title: Structure & File I/O

Background Theory:
File: A file is a container in computer storage devices used for storing data. When
a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates. If you have to enter a large number of data, it
will take a lot of time to enter them all. However, if you have a file containing all
the data, you can easily access the contents of the file using a few commands in C.
You can easily move your data from one computer to another without any
changes.

• Types of Files
i. Text Files
ii. Binary Files
Text Files: Text files are the normal .txt files. You can easily create text files using
any simple text editors such as Notepad. When you open those files, you'll see all
the contents within the file as plain text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least
security and takes bigger storage space.
Binary files: Binary files are mostly the .bin files in your computer. Instead of
storing data in plain text, they store it in the binary form (0's and 1's). They can
hold a higher amount of data, are not readable easily, and provides better security
than text files.

Opening and closing a data file: Before a program can write to a file or read from
a file, the program must open it. Opening a file established a link between the
program and the operating system. This provides the operating system, the name of
the file and the mode in which the file is to be opened. The file that was opened
using fopen( ) function must be closed when no more operations are to be
performed on it.
Syntax:
FILE *ptr_variable; //declaring a file pointer
ptr_variable = fopen( file_name, file_mode); //opening the file using pointer
fclose(ptr_variable);

End of File (EOF): The file reading function need to know the end of file so that
they can stop reading. When the end of file is reached, the opening system sends an
end-of-file signal to the program. When the program receives this signal, the file
reading function returns EOF, which is a constant defined in the file stdio.h and its
value is -1.

LAB 11 : STRUCTURE

1. Write a program to create a structure having members: Name, Address,


Telephone number and Salary of an employee. Read the values of the members
from the user and display.
#include<stdio.h>
struct employee
{
char Name[20];
char Address[20];
long int Telephone;
long int Salary;
};
int main(){
struct employee p[4];
for (int i = 0; i < 4; i++){
printf("Enter your name : ");
scanf(" %[^\n]",p[i].Name);
printf("Enter your address : ");
scanf(" %[^\n]",p[i].Address);
printf("Enter your telephone-number : ");
scanf("%ld",&p[i].Telephone);
printf("Enter your salary : ");
scanf("%ld",&p[i].Salary);
printf("\n");
}
for (int i = 0; i < 4; i++)
printf("\nName:%s \t Address:%s \t Telephone Number:%ld \t
Salary:%ld",p[i].Name,p[i].Address,p[i].Telephone,p[i].Salary);
return 0;
}
OUTPUT:
2. Create a structure employee containing name as character string,
telephone as character string and salary as integer. Input records of 10
employees. After that, display the name, telephone and salary of the
employees with highest salary and lowest salary and display the average
salary of all 10 employees.
#include<stdio.h>
struct employee
{
char Name[20];
char Telephone[14];
long int Salary;
};
int main(){
struct employee p[10];
long int sum=0,average;
for (int i = 0; i < 10; i++){
printf("Enter your name : ");
scanf(" %[^\n]",p[i].Name);
printf("Enter your telephone-number : ");
scanf("%s",p[i].Telephone);
printf("Enter your salary : ");
scanf("%ld",&p[i].Salary);
printf("\n");
}
struct employee temp;
//highest
for (int i = 0; i < 10; i++){
for (int j = i+1; j < 10; j++){
if (p[i].Salary<p[j].Salary){
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
printf("\nThe order starting with employee with highest salary is:");
for (int i = 0; i < 10; i++)
printf("\nName:%s \t Telephone Number:%s \t
Salary:%ld",p[i].Name,p[i].Telephone,p[i].Salary);
//lowest
for (int i = 0; i < 10; i++){
for (int j = i+1; j < 10; j++){
if (p[i].Salary>p[j].Salary){
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
printf("\n\nThe order starting with employee with lowest salary is:");
for (int i = 0; i < 10; i++)
printf("\nName:%s \t Telephone Number:%s \t
Salary:%ld",p[i].Name,p[i].Telephone,p[i].Salary);
//average salary
for (int i = 0; i < 10; i++)
sum+=p[i].Salary;
average=sum/10;
printf("\n\nThe average salary of employees is %ld.",average);
return 0;
}

3. Create a structure Date containing three members: int dd, int mm, int yy.
Create another structure person containing four members: name, address,
telephone and date of birth. For member date of birth, create an object of
structures date inside person. Using these structures, write a program to input
the records until the user enters ‘n’ or ‘N’. Then, display the contents in tabular
form.
#include<stdio.h>
struct date
{
int dd;
int mm;
int yyyy;
};
struct person
{
char name[50];
char address[50];
long int telephone;
struct date date_of_birth;
};
int main(){
char exit;
int i=0,j;
struct person p[30];
while (exit!='n' && exit!='N'){
printf("\nEnter your name : ");
scanf(" %[^\n]",p[i].name);
printf("Enter your address : ");
scanf(" %[^\n]",p[i].address);
printf("Enter your telephone number : ");
scanf("%ld",&p[i].telephone);
printf("Enter date of birth [dd mm yyyy] : ");
scanf("%d%d%d",&p[i].date_of_birth.dd,&p[i].date_of_birth.mm,&p[i].date_of_birth.yyyy
);
printf("\n");
printf("Press 'n' or 'N' to exit and any others to continue.\n");
scanf(" %c",&exit);
i++;
}
printf("\nName \t\t Address \t Telephone.NO \t Date of Birth");
for (j = 0; j < i; j++)
printf("\n%s \t %s \t %ld \t %d-%d-
%d",p[j].name,p[j].address,p[j].telephone,p[j].date_of_birth.dd,p[j].date_of_birth.mm,p[j].date_o
f_birth.yyyy);
return 0;
}
OUTPUT:
4. Create a structure TIME containing hour, minutes and seconds as its
member. Write a program that uses this structure to input start time and
stop time in main(). Pass the structures to a function that calculates the
sum and difference of start time and stop time. Display sum and difference
from main().
#include<stdio.h>
struct Time
{
int hours;
int minutes;
int seconds;
};
void sum_diff(struct Time a,struct Time b,struct Time *c,struct Time *d);
int main(){
struct Time start_time,stop_time,sum,diff;
printf("Enter the start time (hours minutes seconds): ");
scanf("%d%d%d",&start_time.hours,&start_time.minutes,&start_time.seconds);
printf("Enter the stop time (hours minutes seconds): ");
scanf("%d%d%d",&stop_time.hours,&stop_time.minutes,&stop_time.seconds);
sum_diff(start_time,stop_time,&sum,&diff);
printf("\nThe sum of start time and stop time is %d hours %d minutes %d
seconds.",sum.hours,sum.minutes,sum.seconds);
printf("\nThe difference of start time and stop time is %d hours %d minutes %d
seconds.",diff.hours,diff.minutes,diff.seconds);
return 0;
}
void sum_diff(struct Time a,struct Time b,struct Time *c,struct Time *d){
c->hours=a.hours+b.hours;

if ((a.minutes+b.minutes)==60){
c->minutes=0;
c->hours+=1;
}
else if ((a.minutes+b.minutes)>60){
c->minutes=a.minutes+b.minutes-60;
c->hours+=1;
}
else
c->minutes=a.minutes+b.minutes;

if ((a.seconds+b.seconds)==60){
c->seconds=0;
c->minutes+=1;
}
else if ((a.seconds+b.seconds)>60){
c->seconds=a.seconds+b.seconds-60;
c->minutes+=1;
}
else
c->seconds=a.seconds+b.seconds;

d->hours=b.hours-a.hours;
if ((b.minutes-a.minutes)<0)
d->minutes=-(b.minutes-a.minutes);
else
d->minutes=b.minutes-a.minutes;
if ((b.seconds-a.seconds)<0)
d->seconds=-(b.seconds-a.seconds);
else
d->seconds=b.seconds-a.seconds;
}
OUTPUT:
5. Write a program to compute any two instant memory spaces in a format
(Kilobytes: Bytes: Bits) using structure. Build functions to add and subtract
given memory spaces where 1KB=1024B and 1B=8 bits and display the
results from the main().
#include<stdio.h>
struct memory
{
int Kilobytes;
int Bytes;
int Bits;
};
void sum_diff(struct memory a,struct memory b,struct memory *c,struct memory
*d);
int main(){
struct memory first_memory,second_memory,sum,diff;
printf("Enter the first memory (Kilobytes Bytes Bits): ");
scanf("%d%d%d",&first_memory.Kilobytes,&first_memory.Bytes,&first_mem
ory.Bits);
printf("Enter the second memory (Kilobytes Bytes Bits): ");
scanf("%d%d%d",&second_memory.Kilobytes,&second_memory.Bytes,&seco
nd_memory.Bits);
sum_diff(first_memory,second_memory,&sum,&diff);
printf("\nThe sum of first memory and second memory is %d Kilobytes %d
Bytes %d Bits.",sum.Kilobytes,sum.Bytes,sum.Bits);
printf("\nThe difference of first memory and second memory is %d Kilobytes
%d Bytes %d Bits.",diff.Kilobytes,diff.Bytes,diff.Bits);
return 0;
}
void sum_diff(struct memory a,struct memory b,struct memory *c,struct memory
*d){
c->Kilobytes=a.Kilobytes+b.Kilobytes;

if ((a.Bytes+b.Bytes)==1024){
c->Bytes=0;
c->Kilobytes+=1;
}
else if ((a.Bytes+b.Bytes)>1024){
c->Bytes=a.Bytes+b.Bytes-1024;
c->Kilobytes+=1;
}
else
c->Bytes=a.Bytes+b.Bytes;

if ((a.Bits+b.Bits)==8){
c->Bits=0;
c->Bytes+=1;
}
else if ((a.Bits+b.Bits)>8){
c->Bits=a.Bits+b.Bits-8;
c->Bytes+=1;
}
else
c->Bits=a.Bits+b.Bits;

d->Kilobytes=b.Kilobytes-a.Kilobytes;

if ((b.Bytes-a.Bytes)<0)
d->Bytes=-(b.Bytes-a.Bytes);
else
d->Bytes=b.Bytes-a.Bytes;

if ((b.Bits-a.Bits)<0)
d->Bits=-(b.Bits-a.Bits);
else
d->Bits=b.Bits-a.Bits;
}
OUTPUT:

LAB 12 : FILE I/O


1.Write a program to read years from the user and write to a file only if it is the
leap year.
#include<stdio.h>
#include<stdlib.h>
int main(){
int year,read;
FILE *fp;
printf("Enter any year : ");
scanf("%d",&year);
if (year%4==0){
if ((fp=fopen("./files/leapyears.txt","w+"))==NULL){
printf("The file can't be opened.");
exit(1);
}
else
fprintf(fp,"%d",year);
printf("The entered year is leapyear and written in file.");
rewind(fp);
printf("\nThe leap year written in file is : ");
fscanf(fp,"%d",&read);
printf("%d",read);
fclose(fp);
}
else
printf("Enter a leap year if you want to write in a file.");
return 0;
}

2. Write a program to read words from the user until the user enters ‘NO’ and
write them to a file if the word is vowel free. Display the content of the file.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct word_collection
{
char word[30];
};
int check_vowel(char a[30]);
int main(){
char word[30],end[3]="No",ch;
int check,i=0,j=0,k=0;
FILE *fp;
printf("Hint[Enter 'No' if you exit.]\n");
struct word_collection all[100],filtered[50];
do
{
printf("Enter any word : ");
scanf("%s",word);
check=strcmp(word,end);
if (check!=0){
strcpy(all[i].word,word);
i++;
}
} while (check!=0);
while (j<i){
if (check_vowel(all[j].word)==0){
strcpy(filtered[k].word,all[j].word);
k++;
}
j++;
}

if ((fp=fopen("./files/words.txt","w+"))==NULL){
printf("File can't be opened.");
exit(1);
}
else{
for (i = 0; i < k; i++)
fprintf(fp,"\n%s",filtered[i].word);
printf("\nThe vowel free words have been written in a file.\n");
rewind(fp);
printf("\nThe contents of a file are:");
while (1){
if (feof(fp))
break;
else{
ch=fgetc(fp);
printf("%c",ch);
}
}
}
fclose(fp);
return 0;
}
int check_vowel(char a[30]){
int vowel;
for (int i = 0; a[i]!='\0'; i++){
if (a[i]=='a' || a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u' || a[i]=='A' || a[i]=='E' ||
a[i]=='I' || a[i]=='O' || a[i]=='U')
return 1;
else
vowel=0;
}
return 0;
}

3. Write a program to open a new file, read roll number, name, address and
phone number of students until the user says “no” after reading the data, write
it to the file then display the content of the file.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student
{
int roll_no;
char name[30];
char address[30];
long int telephone_no;
};
int main(){
FILE *fp;
char end[3]="No",ch,criteria[4];
int i=0,check;
struct Student info[50];
do
{
printf("\nEnter student's roll number : ");
scanf("%d",&info[i].roll_no);
printf("Enter student's name : ");
scanf(" %[^\n]",info[i].name);
printf("Enter student's address : ");
scanf(" %[^\n]",info[i].address);
printf("Enter student's telephone : ");
scanf("%ld",&info[i].telephone_no);
printf("Enter 'No' to exit and 'Yes' to continue.\n");
scanf("%s",criteria);
check=strcmp(end,criteria);
i++;
} while (check!=0);
if ((fp=fopen("./files/students.txt","w+"))==NULL){
printf("The file can't be opened.");
exit(1);
}
else{
for (int j = 0; j < i; j++)
fprintf(fp,"\n Roll.no:%d \n Name:%s \n Address:%s \n Telephone
number:%ld \n",info[j].roll_no,info[j].name,info[j].address,info[j].telephone_no);
printf("\nThe contents have been written in the file.\n");
printf("\nThe contents of the file is:\n");
rewind(fp);
while (1){
ch=fgetc(fp);
if (feof(fp))
break;
else
printf("%c",ch);
}
}
fclose(fp);
return 0;
}

4. Write a program to input name, roll, address, telephone number and score of
a student. Store the contents of the person in file first.txt. After that, copy the
content of first.txt to second.txt and display the content of second.txt. In this
program, you should use the text file. [You can use structure for data
handling]
#include<stdio.h>
#include<stdlib.h>
struct Student
{
char name[30];
int roll_no;
char address[30];
long int telephone_no;
float score;
};
int main(){
FILE *fp1,*fp2;
char ch;
struct Student info[5];
for (int i = 0; i < 5; i++){
printf("\nEnter student's name : ");
scanf(" %[^\n]",info[i].name);
printf("Enter student's roll number : ");
scanf("%d",&info[i].roll_no);
printf("Enter student's address : ");
scanf(" %[^\n]",info[i].address);
printf("Enter student's telephone : ");
scanf("%ld",&info[i].telephone_no);
printf("Enter student's score : ");
scanf("%f",&info[i].score);
}
if ((fp1=fopen("./files/first.txt","w+"))==NULL){
printf("The file can't be opened.");
exit(1);
}
else{
for (int i = 0; i < 5; i++)
fprintf(fp1,"\n %s \n %d \n %s \n %ld \n %f
\n",info[i].name,info[i].roll_no,info[i].address,info[i].telephone_no,info[i].score);
rewind(fp1);
if ((fp2=fopen("./files/second.txt","w+"))==NULL){
printf("The file can't be opened.");
exit(1);
}
else{
while (1){
if (feof(fp1))
break;
else{
ch=fgetc(fp1);
fputc(ch,fp2);
}
}
rewind(fp2);
while (1){
if (feof(fp2))
break;
else{
ch=fgetc(fp2);
printf("%c",ch);
}
}
}
fclose(fp2);
}
fclose(fp1);
return 0;
}
5. Modify question no. 4, using binary file. You should use fwrite() function to
write data into a file and fread() functions to read data from the file. [Here, you
must use structure for data handling]
#include<stdio.h>
#include<stdlib.h>
struct Student
{
char name[30];
int roll_no;
char address[30];
long int telephone_no;
float score;
};
int main(){
FILE *fp1,*fp2;
char ch;
struct Student info[3],read[3],write[3];
for (int i = 0; i < 3; i++){
printf("\nEnter student's name : ");
scanf(" %[^\n]",info[i].name);
printf("Enter student's roll number : ");
scanf("%d",&info[i].roll_no);
printf("Enter student's address : ");
scanf(" %[^\n]",info[i].address);
printf("Enter student's telephone : ");
scanf("%ld",&info[i].telephone_no);
printf("Enter student's score : ");
scanf("%f",&info[i].score);
}
if ((fp1=fopen("./files/first.bin","wb+"))==NULL){
printf("The file can't be opened.");
exit(1);
}
else{
for (int i = 0; i < 3; i++)
fwrite(&info[i],sizeof(struct Student),1,fp1);
rewind(fp1);
if ((fp2=fopen("./files/second.bin","wb+"))==NULL){
printf("The file can't be opened.");
exit(1);
}
else{
for (int i = 0; i < 3; i++)
fread(&read[i],sizeof(struct Student),1,fp1);
for (int i = 0; i < 3; i++)
fwrite(&read[i],sizeof(struct Student),1,fp2);
rewind(fp2);
for (int i = 0; i < 3; i++)
fread(&write[i],sizeof(struct Student),1,fp2);
for (int i = 0; i < 3; i++)
printf("\n Name : %s \n Roll.No : %d \n Address : %s \n Telephone.No :
%ld \n Score : %f
\n",write[i].name,write[i].roll_no,write[i].address,write[i].telephone_no,write[i].sc
ore);
}
fclose(fp2);
}
fclose(fp1);
return 0;
}

• Analysis and Discussion:


In Lab 11 & Lab 12 we solved the programs using structure and file input /
output operation and modes. Among different modes of file operation or handling like
read(r), write(w), append(a), read and write(r+, a+, w+) and fopen() and fclose() for
opening and closing a file, we used w+ mode to read and write to a file.

You might also like