Tuesday, March 22, 2011

Structures and Unions

Design a structure student_record to contain name, date of birth and total marks obtained. Use the date structure designed in previous program to represent the date of birth.
Develop a program to read data for 10 students in a class and list them rank-wise.

#include <stdio.h>
#include <string.h>
struct student_record
{
char name[20];
int marks;
struct
{
int day;
int month;
int year;
}birth;
}student[10];
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf("Student name:");
scanf("%s",&student[i].name);
printf("Date of Birth:");
scanf("%d %d %d",&student[i].birth.day,&student[i].birth.month,&student[i].birth.year);
printf("Marks obtained:");
scanf("%d",&student[i].marks);
}
printf("\nStudent Name      DOB      Marks\n");
for(i=1;i<=10;i++)
printf("%-15s %2d/%2d/%4d %-5d\n",student[i].name,student[i].birth.day,student[i].
birth.month,student[i].birth.year,student[i].marks);
getch();
}

Structures and Unions

Define a structure called cricket that will describe the following information:
Player name
team name
batting average
Using cricket, declare an array player with 50 elements and write a program to read the information about all the 50 players and print a team-wise list containing names of players with their batting average.

#include <stdio.h>
struct cricket
{
char name[20];
char team[25];
int batting;
};
void main()
{
int i=1,j,temp;
char dummy[25];
struct cricket player[60];
clrscr();
printf("This program is designed for collect cricket player information\n");
while(i<=50)
{
printf("Player Name:");
scanf("%s",player[i].name);
printf("Team Name:");
scanf("%s",player[i].team);
printf("Batting Average:");
scanf("%d",&player[i].batting);
i++;
}
clrscr();
for(i=1;i<50;i++)
for(j=i+1;j<=50;j++)
{
if(strcmp(player[i].team,player[j].team)>0)
{
strcpy(dummy,player[i].team);
strcpy(player[i].team,player[j].team);
strcpy(player[j].team,dummy);
strcpy(dummy,player[i].name);
strcpy(player[i].name,player[j].name);
strcpy(player[j].name,dummy);
temp=player[i].batting;
player[i].batting=player[j].batting;
player[j].batting=temp;
}
}
printf("Team Name       Player Name     Batting Average\n");
for(i=1;i<=50;i++)
printf("%-15s %-15s %10d\n",player[i].team,player[i].name,player[i].batting);
getch();
}

Structures and Unions

Define a structure that can describe an hotel. It should have members that include the name, address, grade, average room charge, and number of rooms.
Write functions to perform the following operations:
  • To print out hotels of a given grade in order of charges
  • To print out hotels with room charges less than a given value
#include <stdio.h>
struct hotel
{
char name[20];
char add[20];
int grade;
int arc;
int rooms;
};
void output();
void out();
struct hotel inn[]={
{"PLAZA","G-99,DELHI",3,4500,50},
{"MYUR","E-45,NOIDA",4,5000,100},
{"RAJDOOT","H-44,DELHI",2,4000,50},
{"SAMRATH","B-75,BOMBAY",5,6000,200},
{"SURYA","A-77,NOIDA",1,3500,150}
};
void main()
{
int go;
clrscr();
printf("Enter 1 for grade search\n");
printf("Enter 2 to search by charge:");
scanf("%d",&go);
switch(go)
{
case 1: output();
break;
case 2: out();
break;
default:printf("Wrong input");
break;
}
getch();
}
void output()
{
int gr,i;
printf("Enter Grade 1 to 5:");
scanf("%d",&gr);
if(gr>=1||gr<=5)
{
for(i=0;i<=4;i++)
{
if(inn[i].grade==gr)
printf("Hotel Name: %s\nAddress:%s\nGrade:%d\nAverage Room charge:%d\n\
Number of Rooms:%d",inn[i].name,inn[i].add,inn[i].grade,inn[i].arc,inn[i].rooms);
}
}
else
printf("Wrong grade input!");
}
void out()
{
int ch,i=0;
printf("Enter the Room charges not greater than 6000:");
scanf("%d",&ch);
while(i<5)
{
if(inn[i].arc<ch)
printf("Hotel Name: %s\nAddress:%s\nGrade:%d\nAverage Room charge:%d\n\
Number of Rooms:%d\n",inn[i].name,inn[i].add,inn[i].grade,inn[i].arc,inn[i].rooms);
i++;
}
}

OUTPUT
Enter 1 for grade search
Enter 2 to search by charge: 1
Enter grade 1 to 5: 1
Hotel Name : SURYA
Address: A-77, NOIDA
Grade: 1
Average Room Charge: 3500
Number of Rooms: 150

Enter 1 for grade search
Enter 2 to search by charge: 1
Enter grade 1 to 5: 2
Enter the Room Charges not greater than 6000: 4500
Hotel Name : RAJDOOT
Address: H-44, DELHI
Grade: 2
Average Room Charge: 4000
Number of Rooms: 50
Hotel Name : SURYA
Address: A-77, NOIDA
Grade: 1
Average Room Charge: 3500
Number of Rooms: 150

Structures and Unions

Create two structures named metric and British which store the values of distances. The matric structure stores the values in metres and centimetres and the British structure stores the values in feet and inches. Write a program that reads value for the structure variables and adds values contained in one variable of metric to the contents of another variables of British. The program should display the result in the format of feet and inches or metres and centimeters as required.

#include <stdio.h>
struct metric
{
int metre;
int centimetre;
};
struct british
{
int feet;
int inches;
};
void main()
{
int inch,CM,centimetre;
struct metric met;
struct british bri;
clrscr();
printf("Enter distance in metre and centimetre m cm:");
scanf("%d %d",&met.metre,&met.centimetre);
printf("Enter the distance in feet and inches f in:");
scanf("%d %d",&bri.feet,&bri.inches);
inch=bri.inches+bri.feet*12;
centimetre=met.centimetre+met.metre*100;
CM=inch*2.54;
met.metre=0;
met.metre=(CM+centimetre)/100;
met.centimetre=0;
met.centimetre=(CM+centimetre)%100;
printf("Addition of these distance: %d metre and %d centimetre",met.metre,met.centimetre);
getch();
}

OUTPUT
Enter distance in metre and centimetre m cm: 25 80
Enter the distance in feet and inches f in: 10 10
Addition of these distance: 29 metre and 10 centimetre

Structures and Unions

Add a function to the previous program that accepts two vectors as input parameters and return the addition of two vectors.

#include <stdio.h>
struct vector
{
int value[30];
}vec1,vec2,vec3;
struct vector Add(struct vector vec1,struct vector vec2,int n);
int i,n;
void main()
{
struct vector vec4;
int x;
clrscr();
printf("Enter starting value of first vector:");
scanf("%d",&x);
printf("Enter no. of Values:");
scanf("%d",&n);
for(i=1;i<=n;i++)
vec1.value[i]=x*i;
printf("Enter starting element of second vector:");
scanf("%d",&x);
for(i=1;i<=n;i++)
vec2.value[i]=x*i;
vec4=Add(vec1,vec2,n);
printf("First vector\n");
for(i=1;i<=n;i++)
printf("%d,",vec1.value[i]);
printf("\nSecond vector\n");
for(i=1;i<=n;i++)
printf("%d,",vec2.value[i]);
printf("\nAddition of these vector\n");
for(i=1;i<=n;i++)
printf("%d,",vec4.value[i]);
getch();
}
struct vector Add(struct vector vec1,struct vector vec2,int n)
{
for(i=1;i<=n;i++)
vec3.value[i]=vec1.value[i]+vec2.value[i];
return(vec3);
}

OUTPUT
Enter starting value of first vector: 10
Enter no. of Values: 10
Enter starting element of second vector: 10
First vector
10,20,30,40,50,60,70,80,90,100
Second vector
10,20,30,40,50,60,70,80,90,100
Addition of these vector
20,40,60,80,100,120,140,160,180,200

Structures and Unions

Define a structure to represent a vector ( a series of integer values) and write a modular program to perform the following tasks:
  • To create a vector
  • To modify the value fo a given element
  • To multiply by a scalar value
  • To display the vector in the form
             (10, 20, 30, ........... . .. . ..... ....)

#include <stdio.h>
struct vector
{
int value[20];
}vec;
void main()
{
int i,n,x;
clrscr();
printf("Enter the starting value:");
scanf("%d",&x);
printf("Enter no. of value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
vec.value[i]=x*i;
printf("%d,",vec.value[i]);
}
getch();
}

OUTPUT
Enter the starting value: 10
Enter no. of value: 10
10,20,30,40,50,60,70,80,90,100

Structures and Unions

Use the date structure defined in previous program to store two dates. Develop a function that will take these two dates as input and compares them.
  • It returns 1, if the date1 is earlier than date2
  • It returns 0, if the date1 is later date
#include <stdio.h>
struct date
{
int day;
int month;
int year;
};
void compare(struct date date1,struct date date2);
void main()
{
struct date date1,date2;
clrscr();
printf("Enter first date dd mm yyyy:");
scanf("%d %d %d",&date1.day,&date1.month,&date1.year);
printf("Enter Second date dd mm yyyy:");
scanf("%d %d %d",&date2.day,&date2.month,&date2.year);
compare(date1,date2);
getch();
}
void compare(struct date date1,struct date date2)
{
if(date1.year<date2.year)
printf("1");
if(date1.year>date2.year)
printf("0");
if(date1.year==date2.year)
{
if(date1.month<date2.month)
printf("1");
if(date1.month>date2.month)
printf("0");
if(date1.month==date2.month)
{
if(date1.day<date2.day)
printf("1");
if(date1.day>date2.day)
printf("0");
}
}
}

OUTPUT
Enter first date dd mm yyyy: 25 2 2010
Enter Second date dd mm yyyy: 25 2 2011
1

Enter fist date dd mm yyyy: 25 2 2000
Enter Second date dd mm yyyy: 24 2 2000
0

Structures and Unions

Add a function called nextdate to the program designed previously to perform the follwing task;
  • Accepts two arguments, one of the structure data containing the present data and the second and integer that represents the number of days to be added to the present date.
  • Adds the days to the present date and returns the structure containing the next date correctly
Note that the next date may be in the next month or even the next year.

#include <stdio.h>
struct date
{
int day;
int month;
int year;
}dat;
void nextdate(struct date dat, int x);
void main()
{
int y;
clrscr();
printf("Enter day:");
scanf("%d",&dat.day);
printf("Enter month:");
scanf("%d",&dat.month);
printf("Enter year:");
scanf("%d",&dat.year);
printf("Enter days to add:");
scanf("%d",&y);
nextdate(dat,y);
getch();
}
/***********nextdate function****************/
void nextdate(struct date dat, int x)
{
dat.day=dat.day+x;
if(dat.month==2)
{
if(dat.year%4==0)
{
dat.day=dat.day-29;
dat.month++;
}
if(dat.year%4!=0)
{
dat.day=dat.day-28;
dat.month++;
}
}
if(dat.month==1||dat.month==3||dat.month==5||dat.month==7
||dat.month==8||dat.month==10||dat.month==12)
while(dat.day>31)
{
dat.day=dat.day-31;
dat.month=dat.month+1;
}
if(dat.month==4||dat.month==6||dat.month==9||dat.month==11)
while(dat.day>30)
{
dat.day=dat.day-30;
dat.month=dat.month+1;
}
if(dat.month>12)
while(dat.month>12)
{
dat.month=dat.month-12;
dat.year=dat.year+1;
}
printf("Updated date: %d/%d/%d",dat.day,dat.month,dat.year);
end:
}

OUTPUT
Enter day: 25
Enter month: 12
Enter year: 2010
Enter days to add: 10
Updated date: 4/1/2011

Enter day: 25
Enter month: 5
Enter year: 2011
Enter days to add: 10
Updated date: 4/6/2011

Structures and Unions

Modify the input function used in previous program such that it reads a value that represents the date in the form of a long integer, like 19450815 for the date 15-8-1945 (August 15, 1945) and assigns suitable values to the members day, month and year. Use suitable algorithm to convert the long integer 19450815 into year, month and day.

#include <stdio.h>
struct date
{
int day;
int month;
int year;
}dat;
long int input();
void validate(struct date dat);
void print(struct date dat);
void main()
{
long int x,rem;
clrscr();
printf("Enter the date in the format of 19910815 for 1991 August 15:");
x=input();
dat.year=x/10000;
rem=x%10000;
dat.month=rem/100;
dat.day=rem%100;
validate(dat);
getch();
}
long int input()
{
long int a;
scanf("%ld",&a);
return(a);
}
void validate(struct date dat)
{
if(dat.day>31||dat.day<1)
printf("The day should 1 to 31!");
else
if(dat.month>12||dat.month<1)
printf("Month should be 1 to 12 only!");
else
if(dat.month==2)
{
if(dat.day==29)
{
if(dat.year%4!=0)
printf("%d is not a leap year",dat.year);
else
print(dat);
}
else
if(dat.day>29)
printf("February has only 28 or 29 days");
else
print(dat);
 }
 else
if(dat.month==4)
{
if(dat.day>30)
printf("April has only 30 days");
 }
 else
if(dat.month==6)
{
if(dat.day>30)
printf("June has only 30 days");
 }
 else
if(dat.month==9)
{
if(dat.day>30)
printf("September has only 30 days");
}
else
if(dat.month==11)
{
if(dat.day>30)
printf("November has only 30 days");
}
else
print(dat);
}
void print(struct date dat)
{
switch(dat.month)
{
case 1:printf("January %d, %d",dat.day,dat.year);
break;
case 2:printf("February %d, %d",dat.day,dat.year);
break;
case 3:printf("March %d, %d",dat.day,dat.year);
break;
case 4:printf("April %d, %d",dat.day,dat.year);
break;
case 5:printf("May %d, %d",dat.day,dat.year);
break;
case 6:printf("June %d, %d",dat.day,dat.year);
break;
case 7:printf("July %d, %d",dat.day,dat.year);
break;
case 8:printf("August %d, %d",dat.day,dat.year);
break;
case 9:printf("September %d, %d",dat.day,dat.year);
break;
case 10:printf("October %d, %d",dat.day,dat.year);
break;
case 11:printf("November %d, %d",dat.day,dat.year);
break;
case 12:printf("December %d, %d",dat.day,dat.year);
break;
}
}

OUTPUT
Enter the date in ther format of 19910815 for 1991 August 15: 20100520
May 20, 2010

Structure and Unions

Design a function update that accepts the date structure designed previously to increment the date by one day and return the new date. The following rules are applicable:
  • If the date is the last day in a month, month should  be incremented
  • If it is the last day in December, the year should be incremented
  • There are 29 days in February of a leap year
#include <stdio.h>
struct date
{
int day;
int month;
int year;
}dat;
void update(struct date dat);
void main()
{
clrscr();
printf("Enter day:");
scanf("%d",&dat.day);
printf("Enter month:");
scanf("%d",&dat.month);
printf("Enter year:");
scanf("%d",&dat.year);
update(dat);
getch();
}
void update(struct date dat)
{
dat.day=dat.day+1;
if(dat.day>32)
{
printf("Wrong input");
goto end;
}
else
if(dat.month==4||dat.month==6||dat.month==9||dat.month==11)
{
if(dat.day==31)
{
dat.day=1;
dat.month=dat.month+1;
}
if(dat.day>31)
{
printf("This month has only 30 days",dat.month);
goto end;
}
}
if(dat.month==1||dat.month==3||dat.month==5||dat.month==7||dat.month==8||dat.month==10||dat.month==12)
if(dat.day==32)
{
dat.day=1;
dat.month=dat.month+1;
}
if(dat.month==13)
{
dat.day=1;
dat.month=1;
dat.year=dat.year+1;
}
if(dat.month==2)
{
if(dat.day>30)
{
printf("This month has 28 or 29 days");
goto end;
}
if(dat.day==29)
{
dat.day=1;
dat.month=dat.month+1;
}
}
printf("Updated date: %d/%d/%d",dat.day,dat.month,dat.year);
end:
}

OUTPUT
Enter day: 31
Enter month: 12
Enter year: 2010
Updated date: 1/1/2011

Enter day: 28
Enter month: 2
Enter year: 2002
Updated date:  1/3/2002

Structures and Unions

Define a structure data type named date containing three integer members day, month and year. Develop an interactive modular program to perform the following tasks:
  • To read data into structure members by a function
  • To validate the date entered by another function
  • To print the date in the format
                   April 29, 2002
by a third function.
The input data should be three integers like 29,4, and 2002 corresponding to day, month and year. Example of invalid data:
31, 4, 2002 - April has only 30 days
29, 2, 2002 - 2002 is not a leap year

#include <stdio.h>
struct date
{
int day;
int month;
int year;
}dat;
input();
void validate(struct date dat);
void print(struct date dat);
void main()
{
clrscr();
printf("Enter day:");
dat.day=input();
printf("Enter month:");
dat.month=input();
printf("Enter year:");
dat.year=input();
validate(dat);
getch();
}
input()
{
int a;
scanf("%d",&a);
return(a);
}
void validate(struct date dat)
{
if(dat.day>31||dat.day<1)
printf("The day should 1 to 31!");
else
if(dat.month>12||dat.month<1)
printf("Month should be 1 to 12 only!");
else
if(dat.month==2)
{
if(dat.day==29)
{
if(dat.year%4!=0)
printf("%d is not a leap year",dat.year);
else
print(dat);
}
else
if(dat.day>29)
printf("February has only 28 or 29 days");
else
print(dat);
 }
 else
if(dat.month==4)
{
if(dat.day>30)
printf("April has only 30 days");
 }
 else
if(dat.month==6)
{
if(dat.day>30)
printf("June has only 30 days");
 }
 else
if(dat.month==9)
{
if(dat.day>30)
printf("September has only 30 days");
}
else
if(dat.month==11)
{
if(dat.day>30)
printf("November has only 30 days");
}
else
print(dat);
}
void print(struct date dat)
{
switch(dat.month)
{
case 1:printf("January %d, %d",dat.day,dat.year);
break;
case 2:printf("February %d, %d",dat.day,dat.year);
break;
case 3:printf("March %d, %d",dat.day,dat.year);
break;
case 4:printf("April %d, %d",dat.day,dat.year);
break;
case 5:printf("May %d, %d",dat.day,dat.year);
break;
case 6:printf("June %d, %d",dat.day,dat.year);
break;
case 7:printf("July %d, %d",dat.day,dat.year);
break;
case 8:printf("August %d, %d",dat.day,dat.year);
break;
case 9:printf("September %d, %d",dat.day,dat.year);
break;
case 10:printf("October %d, %d",dat.day,dat.year);
break;
case 11:printf("November %d, %d",dat.day,dat.year);
break;
case 12:printf("December %d, %d",dat.day,dat.year);
break;
}
}

OUTPUT
Enter day: 5
Enter month: 2
Enter year: 2010
February 5, 2010

Enter day: 31
Enter month: 4
Enter year: 2010
April has only 30 days

Enter day: 29
Enter month: 2
Enter year: 2002
2002 is not a leap year

Structures and Unions

Design a function update that would accept the data structure designed previously and increments time by one second and returns the new time . (If the increment results is 60 seconds, then the second member is set to zero and the minute member is incremented by one. Then, if the result is 60 minutes, the minute member is set to zero and the hour member is incremented by one. Finally when the hour becomes 24, it is set to zero.)

#include <stdio.h>
void update(struct time t);
struct time
{
int hour;
int minute;
int second;
}t;
void main()
{
clrscr();
printf("Enter hour:");
scanf("%d",&t.hour);
printf("Enter minute:");
scanf("%d",&t.minute);
printf("Enter second:");
scanf("%d",&t.second);
update(t);
getch();
}
void update(struct time t)
{
t.second=t.second+1;
if(t.second==60)
{
t.second=0;
t.minute=t.minute+1;
}
if(t.minute==60)
{
t.minute=0;
t.hour=t.hour+1;
}
if(t.hour==24)
t.hour=0;
printf("Updated time= %d:%d:%d",t.hour,t.minute,t.second);
}

OUTPUT
Enter hour: 23
Enter minute: 59
Enter second: 59
Updated time = 0:0:0

Enter hour: 23
Enter minute: 59
Enter second: 1
Updated time = 23:59:2

Structures and Unions

Modify the previous program such that a function is used to input values to the members and another function to display the time.

#include <stdio.h>
input();
void output(struct time_struct t);
struct time_struct
{
int hour;
int minute;
int second;
};
void main()
{
struct time_struct time;
clrscr();
printf("Enter hour:");
time.hour=input();
printf("Enter minute:");
time.minute=input();
printf("Enter seconds:");
time.second=input();
output(time);
getch();
}
input()
{
int a;
scanf("%d",&a);
return(a);
}
void output(struct time_struct t)
{
printf("%d:%d:%d",t.hour,t.minute,t.second);
}

OUTPUT
Enter hour: 16
Enter minute: 40
Enter seconds: 51
16:40:51

Structure and Unions

Define a structure data type called time_struct containing three members integer hour, integer minute and integer second. Develop a program that would assign values to the individual members and display the time in the following from:
16:40:51
#include <stdio.h>
struct time_struct
{
int hour;
int minute;
int second;
};
void main()
{
struct time_struct time;
clrscr();
time.hour=16;
time.minute=40;
time.second=51;
printf("%d:%d:%d",time.hour,time.minute,time.second);
getch();
}
OUTPUT
16:40:51

Friday, March 11, 2011

Structures and Unions

Book Shop Inventory

#include <stdio.h>
struct record
{
char author[20];
char title[30];
float price;
struct
{
char month[10];
int year;
}
date;
char publisher[10];
int quantity;
};
int look_up(struct record table[],char s1[],char s2[],int m);
void get(char string[]);
void main()
{
char title[30],author[20];
int index, no_of_records;
char response[10],quantity[10];
struct record book[] = {
{"Ritchie","C Language",45.00,"May",1977,"PHI",10},
{"Kochan","Programming in C",75.50,"July",1983,"Hayden",5},
{"Balagurusamy","BASIC",30.00,"January",1984,"TMH",0},
{"Balagurusamy","COBOL",60.00,"December",1988,"Macmillan",25}
};
no_of_records = sizeof(book)/sizeof(struct record);
do
{
printf("Enter title and author name as per the list\n");
printf("\Title:  ");
get(title);
printf("Author: ");
get(author);
index=look_up(book,title,author,no_of_records);
if(index != -1)
{
printf("\n%s %s %.2f %s %d %s\n\n",book[index].author,
book[index].title,
book[index].price,
book[index].date.month,
book[index].date.year,
book[index].publisher);
printf("Enter number of copies:");
get(quantity);
if(atoi(quantity)<book[index].quantity)
printf("Cost of %d copies = %.2f\n",atoi(quantity),book[index].price*atoi(quantity));
else
printf("\nRequired copies not in stock\n\n");
}
else
printf("\nBook not in list\n\n");
printf("\nDo you want any other book? (YES/NO):");
get(response);
}
while(response[0] == 'Y' || response[0] == 'y');
printf("\n\nThank you. Good bye!\n");
getch();
}
void get(char string[])
{
char c;
int i=0;
do
{
c=getchar();
string[i++]=c;
}
while(c!='\n');
string[i-1]='\0';
}
int look_up(struct record table[],char s1[],char s2[], int m)
{
int i;
for(i=0;i<m;i++)
if(strcmp(s1,table[i].title)==0 && strcmp(s2,table[i].author)==0)
return(i);
return(-1);
}


Structure and Unions

Write a simple program to illustrate the method of sending an entire structure as a parameter to a function.

#include <stdio.h>
 struct stores
   {                                                               
       char  name[20];                                             
       float price;                                                
       int   quantity;                                             
   };                                                              
   struct stores update (struct stores product, float p, int q);
   float mul (struct stores stock);
void main()
   {
       float    p_increment, value;
       int      q_increment;
       struct stores item = {"XYZ", 25.75, 12};
       printf("\nInput increment values:");
       printf("   price increment and quantity increment\n");
       scanf("%f %d", &p_increment, &q_increment);
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
       item  = update(item, p_increment, q_increment);
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
       printf("Updated values of item\n\n");
       printf("Name      : %s\n",item.name);
       printf("Price     : %f\n",item.price);
       printf("Quantity  : %d\n",item.quantity);
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
       value  = mul(item);
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
       printf("\nValue of the item  =  %f\n", value);
       getch();
   }
   struct stores update(struct stores product, float p, int q)
   {
       product.price += p;
       product.quantity += q;
       return(product);
   }
   float mul(struct stores stock)
   {
       return(stock.price * stock.quantity);
   }

Structures and Unions

Rewrite the previous program using an array member to represent the three subjects.

#include <stdio.h>
void main()
   {                                                               
       struct  marks                                               
       {                                                           
           int  sub[3];                                            
           int  total;                                             
       };                                                          
       struct marks student[3] =                            
       {45,67,81,0,75,53,69,0,57,36,71,0};                  
       struct marks total={0,0,0,0};
       int  i,j;                                                   
                                                                   
       for(i = 0; i <= 2; i++)                                     
       {                                                           
          for(j = 0; j <= 2; j++)                                  
          {                                                        
             student[i].total += student[i].sub[j];                
             total.sub[j] += student[i].sub[j];                    
          }                                                        
          total.total += student[i].total;                         
       }                                                           
       printf("STUDENT         TOTAL\n");
       for(i = 0; i <= 2; i++)
   printf("Student[%d]      %d\n", i+1, student[i].total);
       printf("\nSUBJECT         TOTAL\n");
       for(j = 0; j <= 2; j++)
   printf("Subject-%d       %d\n", j+1, total.sub[j]);
       printf("\nGrand Total  =  %d\n", total.total);
       getch();
   }

Structures and Unions

The program shown below, We have declared a four-member structure, the fourth one for keeping the student-totals. We have also declared an array total to keep the subject-totals and the grand-total. The grand-total is given by total.total. Note that a member name can be any valid C name and can be the same as an existing structure variable name. The linked name total.total represents the total member of the structure variable total.

#include <stdio.h>
struct marks
   {
       int  sub1;                                                  
       int  sub2;                                                  
       int  sub3;                                                  
       int  total;                                                 
   };                                                              
void main()
   {
       int  i;                                                     
       struct marks student[3] =  {{45,67,81,0},            
                                   {75,53,69,0},            
                                   {57,36,71,0}};           
       struct marks total= {0,0,0,0};
       for(i = 0; i <= 2; i++)                                     
       {                                                           
    student[i].total = student[i].sub1 + student[i].sub2 + student[i].sub3;
           total.sub1 = total.sub1 + student[i].sub1;              
           total.sub2 = total.sub2 + student[i].sub2;              
           total.sub3 = total.sub3 + student[i].sub3;              
           total.total = total.total + student[i].total;           
       }                                                           
       printf("STUDENT        TOTAL\n");
       for(i = 0; i <= 2; i++)
   printf("Student[%d]      %d\n", i+1,student[i].total);
       printf("\nSUBJECT        TOTAL\n");
       printf("%s    %d\n%s    %d\n%s    %d\n","Subject 1   ", total.sub1,"Subject 2   ", total.sub2,"Subject 3   ", total.sub3);
       printf("\nGrand Total =   %d\n", total.total);
       getch();
   }

Structures and Unions

Write a program to illustrate the comparison of structure variables.

#include <stdio.h>
struct class
   {
       int  number;                                                
       char name[20];                                              
       float marks;                                                
   };                                                              
                                                                   
void main()
   {
       int  x;
       struct class student1 = {222,"Reddy", 67.00};
       struct class student2;
       student2 = student1;
       x = ((student2.number ==  student1.number) &&
     (student2.marks  ==  student1.marks)) ? 1 : 0;
       if(x == 1)
      {
  printf("\nstudent1 and student2 are same\n\n");
    printf("%d %s %f\n", student2.number,
    student2.name,
    student2.marks);
       }
       else
    printf("\nstudent1 and student2 are different\n\n");
       getch();
   }

OUTPUT
student1 and student2 are same
222  Reddy  67.000000

Structures and Unions

Define a structure type, struct personal that would contain person name, date of joining and salary. Using this structure,write a program to read this information for one person from the keyboard and print the same on the screen.

#include <stdio.h>
struct personal
{
char name[20];
int day;
char month[10];
int year;
float salary;
};
void main()
{
struct personal person;
printf("Input Values\n");
scanf("%s %d %s %d %f",person.name,&person.day,person.month,&person.year,&person.salary);
printf("%s %d %s %d %f\n",person.name,person.day,person.month,person.year,person.salary);
getch();
}

OUTPUT
Input Values
M.L.Goel  10  January  1945  4500
M.L.Goel  10  January  1945  4500.000000 

Friday, March 4, 2011

User-Defined Functions

Write a function that receives a floating point value x and returns it as a value rounded to two nearest decimal places. For example, the value 123.4567 will be rounded to 123.46 (Hint : Seek help of one of the math functions available in math libraray).

#include <stdio.h>
void roundoff(float num);
void main()
{
float num;
clrscr();
printf("Enter a floating point number to round of that value:");
scanf("%f",&num);
roundoff(num);
getch();
}
void roundoff(float num)
{
printf("Rounded number is: %5.2f",num);
}

OUTPUT
Enter a floating point number to round of that value : 123.4567
Rounded number is : 123.46

User-Defined Functions

In preparing the calender for a year we need to know whether that particular year is leap year or not. Design a function leap ( ) that receives the year as a parameter and returns an appropriate message. What modifications are required if we want to use the function in preparing the actual calender?

#include <stdio.h>
void leap(int year);
void main()
{
int year;
clrscr();
printf("Enter the year from 1500 to 2020\nYou can also enter last two digit\
 it will be taken as 1900's year:");
scanf("%d",&year);
leap(year);
getch();
}
void leap(int year)
{
if(year>0&&year<100)
year=year+1900;
if(year>99&&year<1500||year>2020)
printf("Wront input!");
else
if(year%4==0)
printf("This is the leap year!");
else
if(year%4!=0)
printf("This is not leap year!");
}
OUTPUT
Enter the year from 1500 to 2020
You can also enter last two digit it will be taken as 1900's year : 47
This is not leap year!

Enter the year from 1500 to 2020
You can also enter last two digit it will be taken as 1900's year : 2012
This is the leap year!

Enter the year from 1500 to 2020
You can also enter last two digit it will be taken as 1900's year : 2025
Wrong input!

User-Defined Functions

Write a function that takes an integer parameter m representing the month number of the year and returns the corresponding name of the month. For instance, if m = 3, the month is March. Test your program.

#include <stdio.h>
void month(int m);
void main()
{
int n;
clrscr();
printf("Enter a integer number 1 to 12:");
scanf("%d",&n);
month(n);
getch();
}
void month(int m)
{
switch(m)
{
case 1: printf("January");
break;
case 2: printf("February");
break;
case 3: printf("March");
break;
case 4: printf("April");
break;
case 5: printf("May");
break;
case 6: printf("June");
break;
case 7: printf("July");
break;
case 8: printf("August");
break;
case 9: printf("September");
break;
case 10: printf("October");
break;
case 11: printf("November");
break;
case 12: printf("December");
break;
default: printf("Wrong input!");
break;
}
}

OUTPUT
Enter a integer number 1 to 12 : 1
January

Enter a integer number 1 to 12 : 2
February

Enter a integer number 1 to 12 : 3
March

Enter a integer number 1 to 12 : 12
December

Enter a integer number 1 to 12 : 13
Wrong input!

User-Defined Functions

Design a function locate ( ) that takes two character array s1 and s2 and one integer value m as parameters and inserts the string s2 into s1 immediately after the index m.
Write a program to test the function using a real-life situation. (Hint: s2 may be a missing word in s1 that represents a line of text).

#include <stdio.h>
#include <string.h>
void locate(char s1[30],char s2[20],int m);
void main()
{
char str[30],str1[20];
int n;
clrscr();
printf("Input a string:");
gets(str);
printf("Input one more string:");
scanf("%s",str1);
printf("Enter place to insert second string:");
scanf("%d",&n);
locate(str,str1,n);
getch();
}
void locate(char s1[30],char s2[20],int m)
{
int i;
char str[40];
for(i=0;i<=m-1;i++)
str[i]=s1[i];
str[i]='\0';
strcat(str,s2);
printf("\nString is\n%s",str);
}

User-Defined Functions

Write a program that invokes a function called find() to perform the following tasks:
(a) Recieves a character array and a single character.
(b) Returns 1 if the specified character is found in the array, 0 otherwise.

#include <stdio.h>
#include <string.h>
void find(char str[20],char character);
void main()
{
char str[20],ch;
clrscr();
printf("Enter a String:");
scanf("%s",str);
printf("Enter a character to Search:");
scanf("%s",&ch);
find(str,ch);
getch();
}
void find(char str[20],char character)
{
if(strchr(str,character)!=0)
putchar('1');
else
putchar('0');
}

OUTPUT
Enter a String : PROGRAMMING
Enter a character to Search : M
1

Enter a String : PROGRAMMING
Enter a character to Search : U
0

User-Defined Functions

Develop your own functions for performing following operations on strings:
(a) Copying one string to another
(b) Comparing two strings
(c) Adding a string to the end of another string
Write a driver program to test your functions.

#include <stdio.h>
void Copy(char str[20]);
void Compare(char str1[20],char str2[20]);
void Add(char str1[20],char str2[20]);
void main()
{
char str[20],str1[20],str2[20];
clrscr();
printf("Enter a String:");
scanf("%s",str);
Copy(str);
printf("\nEnter 1st string to compare:");
scanf("%s",str1);
printf("\nEnter 2nd string to compare:");
scanf("%s",str2);
Compare(str1,str2);
Add(str1,str2);
getch();
}
void Copy(char str[20])
{
char string[20];
strcpy(string,str);
printf("Copied string: %s",string);
}
void Compare(char str1[20],char str2[20])
{
if(strcmp(str1,str2)==0)
printf("\nStrings are Equal!");
else
printf("\nStrings are not Equal!");
}
void Add(char str1[20],char str2[20])
{
strcat(str1,str2);
printf("\nAdding of String\n%s",str1);
}

User-Defined Functions

Develop a top-down modular program that will perform the following tasks:
(a) Read two integer arrays with unsorted elements.
(b) Sort them in ascending order
(c) Merge the sorted arrays
(d) Print the sorted list
Use functions for carrying out each of the above tasks. The main function should have only function calls.

#include <stdio.h>
Sort(int Arr[20],int Arr1[20]);
void Merge(int Arr[10],int Arr1[10]);
Read(int a[20],int b[20]);
int n,Arr[20],Arr1[20];
void main()
{
int i,a[20],b[20];
clrscr();
Read(a,b);
Sort(a,b);
Merge(a,b);
getch();
}
Read(int a[20],int b[20])
{
int i;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the elements of first Unsorted Array\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("Enter the elements of second Unsorted Array\n");
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
return(a[20],b[20]);
}
Sort(int Arr[20],int Arr1[20])
{
int i,j,t;
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(Arr[i]>Arr[j])
{
t=Arr[i];
Arr[i]=Arr[j];
Arr[j]=t;
}
if(Arr1[i]>Arr1[j])
{
t=Arr1[i];
Arr1[i]=Arr1[j];
Arr1[j]=t;
}
}
}
printf("First Sorted Array!\n");
for(i=1;i<=n;i++)
printf("%d ",Arr[i]);
printf("\nSecond Sorted Array!\n");
for(i=1;i<=n;i++)
printf("%d ",Arr1[i]);
return(Arr[20],Arr1[20]);
}
void Merge(int Arr[20],int Arr1[20])
{
int i,j,m,t,Arr2[20];
m=n+n;
for(i=1;i<=n;i++)
{
Arr2[i]=Arr[i];
Arr2[n+i]=Arr1[i];
}
for(i=1;i<m;i++)
for(j=i+1;j<=m;j++)
if(Arr2[i]>Arr2[j])
{
t=Arr2[i];
Arr2[i]=Arr2[j];
Arr2[j]=t;
}
printf("\nMerged Sorted Array!\n");
for(i=1;i<=m;i++)
printf("%d ",Arr2[i]);
}

User-Defined Functions

Design and code an interactive modular program that will use functions to a matrix of m by n size, compute column average and row averages, and then print the entire matrix with average shown in respective rows and columns.

#include <stdio.h>
void Average(int A[20][20]);
int m,n;
void main()
{
int i,j,A[20][20];
clrscr();
printf("Enter the number of Rows:");
scanf("%d",&m);
printf("Enter the number of Column:");
scanf("%d",&n);
printf("Enter elements of %dX%d matrix elements\n",m,n);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&A[i][j]);
Average(A);
getch();
}
void Average(int A[20][20])
{
int i,j,Row[10]={0},Col[10]={0};
float avg[10],avg1[10];
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
Col[i]+=A[i][j];
Row[j]+=A[i][j];
}
avg[i]=(float)Col[i]/n;
}
for(j=1;j<=n;j++)
avg1[j]=(float)Row[j]/m;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
printf("%5d",A[i][j]);
}
printf("%7.2f",avg[i]);
putchar('\n');
}
putchar('\n');
for(j=1;j<=n;j++)
printf("%5.2f",avg1[j]);
}

User-Defined Functions

Write a function that can be called to compute the product of two matrices of size m by n and n by m. The main function provides the values for m and n and two matrices.

#include <stdio.h>
void product(int A[20][20],int B[20][20]);
int m,n;
void main()
{
int i,j,Arr[20][20],Brr[20][20];
clrscr();
printf("Enter the value of row(m) and column(n):");
scanf("%d %d",&m,&n);
printf("Enter the elements of first %d x %d matrix\n",m,n);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&Arr[i][j]);
printf("Enter the elemts of second %d x %d matrix\n",n,m);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&Brr[i][j]);
product(Arr,Brr);
getch();
}
void product(int A[20][20],int B[20][20])
{
int i,j,k,C[40][40]={0};
for(i=1;i<=m;i++)
{
for(j=1;j<=m;j++)
{
for(k=1;k<=n;k++)
C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
}
printf("Product of 1st and 2nd Matrix\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=m;j++)
printf("%4d",C[i][j]);
putchar('\n');
}
}

User-Defined Functions

Write a function that can be called to find the largest element of an m by n matrix.

#include <stdio.h>
void largest(int A[20][20]);
void main()
{
int Arr[20][20],i,j;
clrscr();
printf("Enter 5x5 matrix elements \n");
for(i=1;i<=5;i++)
for(j=1;j<=5;j++)
scanf("%d",&Arr[i][j]);
largest(Arr);
getch();
}
void largest(int A[20][20])
{
int i,j,k,l,max,p1,p2;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
max=A[i][j];
p1=i;
p2=j;
for(k=1;k<=5;k++)
{
for(l=1;l<=5;l++)
{
if(A[k][l]>max)
{
max=A[k][l];
p1=k;
p2=l;
}
}
}
}
}
printf("The largest element is A[%d][%d] and the value is %d",p1,p2,max);
}

User-Defined Functions

Develop a modular interactive program using functions that reads the values of three sides of a triangle and displays either its area or its perimeter as per the request of the user. Given the three sides a, b and c.
Perimeter = a +b +c
Area = sqrt((s-a)(s-b)(s-c))
where s = (a+b+c)/2

#include <stdio.h>
#include <math.h>
void perimeter(float a,float b,float c);
void area(float a,float b,float c);
float a,b,c;
void main()
{
int res;
clrscr();
printf("Enter the three sides of triangle\n");
scanf("%f %f %f",&a,&b,&c);
printf("If you want to perimeter press 1\n");
printf("Or You want to Area press 2:");
scanf("%d",&res);
if(res==1)
perimeter(a,b,c);
if(res==2)
area(a,b,c);
getch();
}
void perimeter(float a,float b,float c)
{
float p;
p=a+b+c;
printf("Perimeter of Triangle: %5.2f",p);
}
void area(float a,float b,float c)
{
float A,S;
S=(a+b+c)/2;
A=sqrt((S-a)*(S-b)*(S-c));
printf("Area of Triangle is: %5.2f",A);
}

OUTPUT
Enter the three sides of triangle
5  8  10
If you want to Perimeter press 1
Or you want to Area press 2 : 1
Perimeter of Triangle : 23.00

Enter the three sides of triangle
5  8  10
If you want to Perimeter press 1
Or you want to Area press 2 : 2
Area of triangle is : 5.84

User-Defined Functions

Develop a top_down modular program to implement a calculator. The program should request the user to input two numbers and display one of the follwing as per the desire of the user:
(a) Sum fo the numbers
(b) Difference of the numbers
(c) Product of the numbers
(d) Division of the numbers
Provide separate functions for performing various tasks such as reading,calculating and displaying. Calculating module should call second level modules to perform the individual mathematical operations. The main function shoud have ony function calls.

#include <stdio.h>
float input(void);
void calculation(float x,float y);
void output(float z);
float x,y,z;
void main()
{
clrscr();
input();
calculation(x,y);
getch();
}
float input(void)
{
printf("Enter the value of X and Y\n");
scanf("%f %f",&x,&y);
return(x,y);
}
void calculation(float x,float y)
{
int i;
float z;
printf("To Add these values press 1\nTo Subtract press 2\nTo Product press 3\
\nFor Division press 4:");
scanf("%d",&i);
switch(i)
{
case 1:z=x+y;
break;
case 2:z=x-y;
break;
case 3:z=x*y;
break;
case 4:z=x/y;
break;
}
output(z);
}
void output(float z)
{
printf("Result is: %5.2f",z);
}

OUTPUT
Enter the value of X and Y
255  456
To Add these values press 1
To Subtract press2
To Product press 3
Fo Division press 4 : 1
Result is : 711.00

Enter the value of X and Y
255  456
To Add these values press 1
To Subtract press2
To Product press 3
Fo Division press 4 : 2
Result is : -201.00

Enter the value of X and Y
255  456
To Add these values press 1
To Subtract press2
To Product press 3
Fo Division press 4 : 3
Result is : 116280.00

Enter the value of X and Y
255  456
To Add these values press 1
To Subtract press2
To Product press 3
Fo Division press 4 : 4
Result is : 0.56

User-Defined Functions

Write a function that will scan a character string passed as an argument and convert all lowercase characters into their uppercase equivalents.

#include <stdio.h>
#include <ctype.h>
void UPPERCASE(char str[20]);
void main()
{
char str[20];
clrscr();
printf("Enter a string\n");
scanf("%s",str);
UPPERCASE(str);
getch();
}
void UPPERCASE(char str[20])
{
int i=0;
while(str[i]!='\0')
{
str[i]=toupper(str[i]);
i++;
}
printf("%s",str);
}

OUTPUT
Enter a string
Programming
PROGRAMMING

User-Defined Functions

Write a function prime that returns 1 if its argument is a prime number and returns zero otherwise.

#include <stdio.h>
prime(int x);
void main()
{
int x,y;
clrscr();
printf("Enter a number:");
scanf("%d",&x);
y=prime(x);
printf("%d",y);
getch();
}
prime(int x)
{
int i,y;
for(i=2;i<=x-1;i++)
{
if(x==2)
y=1;
if(x%i==0)
{
y=0;
break;
}
else
y=1;
}
return(y);
}

OUTPUT
Enter a number : 5
1

Enter a number : 6
0

User-Defined Functions

Write a function that will round a floating-point number to an indicated decimal place. For example the number 17.457 would yield the value 17.46 when it rounded off to two decimal places.

#include <stdio.h>
void Round_off(float x);
void main()
{
float x;
clrscr();
printf("Enter a floating point number:");
scanf("%f",&x);
Round_off(x);
getch();
}
void Round_off(float x)
{
int y;
printf("Enter the decimal places to round off the number:");
scanf("%d",&y);
printf("Rounded off number: %5.*f",y,x);
}

User-Defined Function

The Fibonacci numbers are defined recursively as follows:
F1 = 1
F2 = 1
Fn = F n - 1 + F n - 2, n > 2
Write a function that will generate and print the first n Fibonacci numbers. Test the function for n = 5, 10 , and 15.

#include <stdio.h>
void fibonacci(int n);
void main()
{
int n;
clrscr();
printf("Enter the value of Term:");
scanf("%d",&n);
fibonacci(n);
getch();
}
void fibonacci(int n)
{
int total[20],a=1,b=1,i=0;
do
{
total[i]=a+b;
a=b;
b=total[i];
}
while(++i<=n);
for(i=i-2;i>=0;--i)
printf(" %d",total[i]);
}

OUTPUT
Enter the value of Term : 5
13  8  5  3  2

Enter the value of Term : 10
144  89  55  34  21  13  8  5  3  2

Enter the value of Term : 15
1597  987  610  377  233  144  89  55  31  21  13  8  5  3  2

User-Defined Functions

Use recursive function calls to evaluate
f(x) = x - power 3 to x/3! + power 5 to x/5! - power 7 to x/7! + .....

#include <stdio.h>
#include <math.h>
calculate(long double x);
fact(long double y);
void main()
{
long double x, ans;
clrscr();
printf("Enter the value of X:");
scanf("%Lf",&x);
calculate(x);
getch();
}
calculate(long double x)
{
int j=2,i,f;
f=x;
for(i=3;i<11;i=i+2)
{
if(j%2==0)
x=x-pow(f,i)/(fact(i));
else
x=x+pow(f,i)/(fact(i));
j++;
}
printf("Series of your no. = %Lf",x);
return(0);
}
fact(long double y)
{
long double fac;
if(y==1)
return(1);
else
fac=y*fact(y-1);
return(fac);
}

OUTPUT
Enter the value of X : 2
Series of your no. : 0.891059

User-Defined Functions

Write a function exchange to interchange the values of two variables, say x and y. Illustrate the use of this function, in a calling function. Assume that x and y are defined as global variables.

#include <stdio.h>
void exchange(int x,int y);
int x,y;
void main()
{
printf("Enter the value of X:");
scanf("%d",&x);
printf("Enter the value of Y:");
scanf("%d",&y);
exchange(x,y);
getch();
}
void exchange(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("X=%d\nY=%d",x,y);
}

OUTPUT
Enter the value of X : 5
Enter the value of Y : 7
X = 7
Y = 5

User-Defined Functions

Calculation of Area under a Curve

#include <stdio.h>
float start_point,end_point,total_area;
int numtraps;
void main()
{
void input(void);
float find_area(float a,float b,int n);
printf("AREA UNDER A CURVE");
input();
total_area=find_area(start_point,end_point,numtraps);
printf("TOTAL AREA = %f",total_area);
getch();
}
void input(void)
{
printf("\n Enter lower limit:");
scanf("%f",&start_point);
printf("Enter upper limit:");
scanf("%f",&end_point);
printf("Enter number of trapezoids:");
scanf("%d",&numtraps);
}
float find_area(float a,float b, int n)
{
float base,lower,h1,h2;
float function_x(float x);
float trap_area(float h1,float h2,float base);
base = (b-1)/n;
lower=a;
for(lower=a;lower<=b-base;lower=lower+base)
{
h1=function_x(lower);
h1=function_x(lower+base);
total_area+=trap_area(h1,h2,base);
}
return(total_area);
}
float trap_area(float height_1, float height_2,float base)
{
float area;
area=0.5*(height_1+height_2)*base;
return(area);
}
float function_x(float x)
{
return(x*x+1);
}

User-Defined Functions

Write a program to illustrate the properties of a static variable.

#include <stdio.h>
void stat(void);
void main ()
   {
 int i;
 for(i=1; i<=3; i++)
 stat( );
 getch();
   }
void stat(void)
{
   static int x = 0;
   x = x+1;
   printf("x = %d\n", x);
}

OUTPUT
x = 1
x = 2
x = 3

Thursday, March 3, 2011

User-Defined Functions

Write a multifunction program to illustrate the properties of global variables.
A program to illustrates the properties of global variables is presented. Note that variables x is used in all functions but none except fun2, has a definition for x. Because x has been declared 'above' all the functions, it is available to each function without having to pass x as a function argument. Further, since the value of x is directly available, we need not use return(x) statements in fun1 and fun3. However, since fun2 has a definition of x, it returns its local value of x and therefore uses a return statement. In fun2, the global x is not visible. The local x hides its visibility here.

#include <stdio.h>
int fun1(void);
int fun2(void);
int fun3(void);
int x ;   /* global */
void main( )
   {
 x = 10 ;  /* global x */
 printf("x = %d\n", x);
 printf("x = %d\n", fun1());
 printf("x = %d\n", fun2());
 printf("x = %d\n", fun3());
 getch();
   }
   fun1(void)
   {
 return(x = x + 10);
   }
   int fun2(void)
   {
 int x ;   /* local */
 x = 1 ;
 return (x);
   }
   fun3(void)
   {
 return(x = x + 10);  /* global x */
   }

OUTPUT
x = 10
x = 20
x = 1
x = 30

User-Defined Functions

Write a multifunction to illustrate how automatic variables work.
A program with two subprograms function1 and function2 is shown m is an automatic variable and it is declared at the beginning of each function. m is initialized to 10,100, and 1000 in function1, function2 and main respectively. When executed, main calls function2 which in turn calls function1. When main is active, m = 1000; but when function2 is called, the main's m is temporarily put on the shelf and the new local m = 100 becomes active. Similarly, when function1 is called, both the previous values of m are put on the shelf and the latest value of (m=10) becomes active. As soon as function1 (m=10) is finished, function2 (m=100) takes over again. As soon it is done, main (m=1000) takes over. The output clearly shows that the value assigned to m in one function does not affect its value in the other functions; and the local value of m is destroyed when it leaves a function.

#include <stdio.h>
void function1(void);
void function2(void);
void main( )
   {
 int m = 1000;
 function2();
 printf("%d\n",m); /* Third output */
 getch();
   }
   void function1(void)
   {
 int m = 10;
 printf("%d\n",m); /* First output */
   }
                                                        
   void function2(void)                                                
   {                                                          
        int m = 100;                                          
        function1();                                          
        printf("%d\n",m); /* Second output */                                     
   }

OUTPUT
10
100
1000

User-Defined Functions

Write a program that uses a function to sort an array of integers.
A program to sort an array of integers using the function sort() is given. Its output clearly shows that a function can change the values in an array passed as an argument.

#include <stdio.h>
void sort(int m, int x[ ]);
void main()
   {
       int i;
       int marks[5] = {40, 90, 73, 81, 35};
       printf("Marks before sorting\n");
       for(i = 0; i < 5; i++)
   printf("%d ", marks[i]);
       printf("\n\n");
       sort (5, marks);
       printf("Marks after sorting\n");
       for(i = 0; i < 5; i++)
   printf("%-4d", marks[i]);
       printf("\n");                                          
       getch();
   }

User-Defined Functions

Write a program to calculate the standard deviation of an array of values. Thea array elements are read from the terminal. Use functions to calculate standard deviation and mean.

#include <stdio.h>
#include <math.h>
#define SIZE 5
   float std_dev(float a[], int n);
   float mean (float a[], int n);
void main( )
   {
        float value[SIZE];
        int i;                                                
                                                              
        printf("Enter %d float values\n", SIZE);              
        for (i=0 ;i < SIZE ; i++)                             
            scanf("%f", &value[i]);                           
        printf("Std.deviation is %f\n", std_dev(value,SIZE)); 
 getch();
   }
   float std_dev(float a[], int n)                                         
   {    int i;                                                
        float x, sum = 0.0;                           
        x = mean (a,n);                                       
        for(i=0; i < n; i++)                                   
         sum += (x-a[i])*(x-a[i]);                             
        return(sqrt(sum/(float)n));                           
   }                                                          
   float mean(float a[],int n)                                            
   {                                                          
        int i ;                                               
        float sum = 0.0;                                      
        for(i=0 ; i < n ; i++)                                
           sum = sum + a[i];                                  
        return(sum/(float)n);                                 
   }