Lab Report On C-Programming Lab No.: 1 To 12 Title: Introduction and Variables Date: 2079/01/16
Lab Report On C-Programming Lab No.: 1 To 12 Title: Introduction and Variables Date: 2079/01/16
Lab No.: 1 to 12
Title: Introduction and Variables
Date: 2079/01/16
#include<stdio.h>
int main()
{
printf(“Hello World”);
return 0;
}
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:
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, ©);
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:
LAB 2
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:
#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:
#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:
#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:
#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:
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.
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:
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:
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);
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
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
}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);
b. int main()
{
int a=10;
clrscr();
printf(“%d”,a);
a=a+50;
printf(“%d”,a);
return 0;
}
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
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
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:
#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:
#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
#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
• 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:
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);
}
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:
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:
1) n . Here you cannot use pow() function and you should read the value of n
n+1 2
#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);
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:
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]);
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){
}
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
#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:
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:
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:
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:
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:
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: ");
}
}
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");
}
}
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:
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.
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
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:
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;
}