Monday, February 28, 2011

Arrays

Develop a program to implement the binary search algorithm. This technique compares the search key value with the value of the element that is midway in a "sorted" list. Then:
(a) If they match, the search is over.
(b) If the search key value is less than the middle value, then the first half of the list contains the key value.
(c) If the search keay value is greater than the middle value, then the second half contains the key value.
Repeat this "divide-and-conquer" strategy until we have a match. If the list is reduced to one no-matching element, then the list does not contain the key value. Use sorted list.

#include <stdio.h>
main()
{
int top,bottom,middle,value[50],key,n,i;
clrscr();
printf("Enter the number of elements in array:");
scanf("%d",&n);
printf("Enter the elements of array in ascending order\n");
for(i=1;i<=n;i++)
scanf("%d",&value[i]);
printf("Enter the value which you want to search:");
scanf("%d",&key);
top=n-1;
bottom=0;
do
{
middle=(top+bottom)/2;
if(value[middle]<key)
bottom=middle+1;
else
top=middle;
}
while(top>bottom);
if(top==-1)
printf("List is empty!");
else if(value[top]==key)
printf("value has been found!");
else
printf("Target value has not been found!");
getch();
}
OUTPUT
Enter the number of elements in array: 10
Enter the elements of array in ascending order
1 2 3 4 5 6 7 8 9 11
Enter the value which you want to search: 7
value has been found!

Enter the number of elements in array: 10
Enter the elements of array in ascending order
1 2 3 4 5 6 7 8 9 11
Enter the value which you want to search: 12
Target value has not been found!

Arrays

Selection sort is based on the follwing idea:
Selecting the largest array element and swapping it with the last array element leaves an unsorted list whose size is 1 less than the size of the original list. If we repeat this step again on the usorted list we will have an ordered list of size 2 and an unsorted list size n-2. When we repeat thist until the size of the unsorted list becomes one, the result will be a sorted list.
Write a program to implement this algorithm.

#include <stdio.h>
void main()
{
int i,j,min,pos,arr[200],size;
clrscr();
printf("Enter the number of elements of array:");
scanf("%d",&size);
printf("Enter the elements fo array\n");
for(i=1;i<=size;i++)
scanf("%d",&arr[i]);
for(i=1;iA<size-1;i++)
{
min=arr[i];
pos=i;
for(j=i+1;j<size;j++)
{
if(arr[j]<min)
{
min=arr[j];
pos=j;
}
}
arr[pos]=arr[i];
arr[i]=min;
}
for(i=1;i<=size;i++)
printf("%d ",arr[i]);
getch();
}

Arrays

Write a program that fills a five-by-five matrix as follows:
  • Upper left triangle with +1s
  • Lower right triangle with -1s
  • Right to left diagonal with zeros
Display the contents of the matrix using not more than two printf statements

#include <stdio.h>
main()
{
int a[10][10],i,j;
clrscr();
printf("This is 5x5 Matrix\n");
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i+j<=5)
a[i][j]=+1;
else if(i+j>=7)
a[i][j]=-1;
else
a[i][j]=0;
printf("%3d",a[i][j]);
}
putchar('\n');
}
getch();
}

Arrays

Two matrices that have the same number of rows and columns can be multiplied to produce a third matrix.The product of A and B is a third matrix C of size nxn where each elements of C is given by the following equation.
Cij = aikbkj
Write a program that will read the values of elements of A and B and produce the product matrix C.

#include <stdio.h>
main()
{
int a[10][10],b[10][10],c[100][100]={0},i,j,k,n;
clrscr();
printf("Enter no. of Rows and column:");
scanf("%d",&n);
printf("Enter the elements of first %dx%d matrix\n",n,n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("Enter the element of second %dx%d matrix\n",n,n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&b[i][j]);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
for(k=1;k<=n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
printf("%4d",c[i][j]);
}
putchar('\n');
}
getch();
}

Arrays

The annual examination of 100 students are tabulated. Write a program to read the data and determine the following:
(a) Total marks obtained by each student.
(b) The highest marks in each subject and the Roll No. of the student who seured it.
(c) The student who obtained the highest total marks.

#include <stdio.h>
void main()
{
int max,pos,k;
int i,j,marks[100][100],total[100]={0},n;
clrscr();
printf("Enter the number of student:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the marks of Roll no.%d in three subjects\n",i);
for(j=1;j<=3;j++)
{
scanf("%d",&marks[i][j]);
total[i]=total[i]+marks[i][j];
}
}
printf("Roll no. T.Marks\n");
for(i=1;i<=n;i++)
printf("%4d %8d\n",i,total[i]);
for(i=1;i<=n-1;i++)
{
max=marks[i][1];
pos=i;
for(k=1;k<=n;k++)
{
if(marks[k][1]>max)
{
max=marks[k][1];
pos=k;
}
}
}
printf("Maximum marks obtain in subject 1 by Roll no.%d and his marks=%d\n",pos,max);
for(i=1;i<=n-1;i++)
{
max=marks[i][2];
pos=i;
for(k=1;k<=n;k++)
{
if(marks[k][2]>max)
{
max=marks[k][2];
pos=k;
}
}
}
printf("Maximum marks obtain in subject 2 by Roll no.%d and his marks=%d\n",pos,max);
for(i=1;i<=n-1;i++)
{
max=marks[i][3];
pos=i;
for(k=1;k<=n;k++)
{
if(marks[k][3]>max)
{
max=marks[k][3];
pos=k;
}
}
}
printf("Maximum marks obtain in subject 3 by Roll no.%d and his marks=%d\n",pos,max);
for(i=1;i<=n-1;i++)
{
max=total[i];
pos=i;
for(k=1;k<=n;k++)
{
if(total[k]>max)
{
max=total[k];
pos=k;
}
}
}
printf("Highest total marks obtain by Roll no.%d and his T.marks=%d\n",pos,max);
getch();
}

Arrays

An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast fot each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the ballot should be considered as a 'spoilt ballot' and the program should also count the number of spoilt ballots.

#include <stdio.h>
void main()
{
int group[5]={0,0,0,0,0},i,value[150];
int spoilt=0;
clrscr();
printf("To Vote Rajesh press 1\nTo vote Ravi press 2\n\
To vote sunil press 3\nTo vote sameer press 4\nTo vote \
Raj press 5\nTo exit voting press -99\n\n");
for(i=1;i<=100;i++)
{
scanf("%d",&value[i]);
++group[value[i]];
if(value[i]>5)
spoilt++;
else if(value[i]==-99)
break;
}
printf("Rajesh got %d votes\n",group[1]);
printf("Ravi got %d votes\n",group[2]);
printf("Sunil got %d votes\n",group[3]);
printf("Sameer got %d votes\n",group[4]);
printf("Raj got %d votes\n",group[5]);
printf("%d votes has been spoilt",spoilt);
getch();
}

Arrays

The daily maximum temperatures recorded in 10 cities during the month of January (for 10 days) have been tabulated. Write a program to read the table elements into a two-dimensional array temprature, and to find the city and day corresponding to
(a) the highest temperature and
(b) the lowest temperature.

#include <stdio.h>
#define Day 5
#define City 10
void main()
{
int i,j;
float value[62][20];
clrscr();
printf("Enter the temperature of 10 cities in january month\n");
for(i=1;i<=Day;i++)
{
for(j=1;j<=City;j++)
scanf("%f",&value[i][j]);
}
printf(" City\n");
printf("Day ");
for(j=1;j<=City;j++)
printf("%d     ",j);
putchar('\n');
for(i=1;i<=Day;i++)
{
printf("%d ",i);
for(j=1;j<=City;j++)
printf("%5.2f ",value[i][j]);
putchar('\n');
}
getch();
}

Arrays

Write a program for fitting a straight line through a set of points (xi,yi), i = 1, ..., n.
The straight line equation is y = mx + c
and the value of m and c are given by
m=(n*(x[i]*y[i])-(x[i])*(y[i]))/(n*(x[i]*x[i])-(x[i]*x[i]));
c=(1/n)*(y[i]-m*x[i]);

All summations are from 1 to n.

#include <stdio.h>
void main()
{
int i,x[10],y[10],n;
float m,c,line;
clrscr();
printf("Enter the value of terms:");
scanf("%d",&n);
printf("Enter the value of xi and yi\n");
for(i=1;i<=n;i++)
scanf("%d %d",&x[i],&y[i]);
for(i=1;i<=n;i++)
{
m=(n*(x[i]*y[i])-(x[i])*(y[i]))/(n*(x[i]*x[i])-(x[i]*x[i]));
c=(1/n)*(y[i]-m*x[i]);
printf("m = %5.2f C = %5.2f\n",m,c);
}
for(i=1;i<=n;i++)
{
line=m*x[i]+c;
printf("y = mx+c = %5.2f\n",line);
}
getch();
}

Arrays

Production and Sales Analysis

#include <stdio.h>
void main()
{
int M[5][6],S[5][6],C[6],Mvalue[5][6],Svalue[5][6],Mweek[5],Sweek[5],
Mproduct[6],Sproduct[6],Mtotal,Stotal,i,j,number;
clrscr();
printf("Enter products manufactured week_wise \n");
printf("M11,M12,---,M21,M22,--etc\n");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
scanf("%d",&M[i][j]);
printf("Enter products sold week_wise\n");
printf("S11,S12,--,S21,S22--etc\n");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
scanf("%d",&S[i][j]);
printf("Enter cost of each product\n");
for(j=1;j<=5;j++)
scanf("%d",&C[j]);
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
{
Mvalue[i][j]=M[i][j]*C[j];
Svalue[i][j]=S[i][j]*C[j];
}
for(i=1;i<=4;i++)
{
Mweek[i]=0;
Sweek[i]=0;
for(j=1;j<=5;j++)
{
Mweek[i]+=Mvalue[i][j];
Sweek[i]+=Svalue[i][j];
}
}
for(j=1;j<=5;j++)
{
Mproduct[j]=0;
Sproduct[j]=0;
for(i=1;i<=4;i++)
{
Mproduct[j]+=Mvalue[i][j];
Sproduct[j]+=Svalue[i][j];
}
}
Mtotal=Stotal=0;
for(i=1;i<=4;i++)
{
Mtotal+=Mweek[i];
Stotal+=Sweek[i];
}
printf("\nFollwing is the list of things you can\n");
printf("Request for Enter appropriate item number\n");
printf("and press RETURN key\n");
printf("1.Value matrices of production & sales\n");
printf("2.Total value of weekly production & sales\n");
printf("3.Product_wise monthly value of production &");
printf("sales\n");
printf("4.Grand total value of production & sales\n");
printf("5.Exit\n");
number=0;
while(1)
{
printf("\nENTER YOUR CHOISE:");
scanf("%d",&number);
printf("\n");
if(number==5)
{
printf("G O O D  B Y E\n\n");
break;
}
switch(number)
{
case 1:
printf("VALUE MATRIX OF PRODUCTION\n\n");
for(i=1;i<=4;i++)
{
printf(" Week(%d)",i);
for(j=1;j<=5;j++)
printf("%7d",Mvalue[i][j]);
printf("\n");
}
printf("\nVALUE MATRIX OF SALES\n\n");
for(i=1;i<=4;i++)
{
printf(" Week(%d)\t",i);
for(j=1;j<=5;j++)
printf("%7d",Svalue[i][j]);
printf("\n");
}
break;
case 2: 
printf("TOTAL WEEKLY PRODUCTION & SALES\n\n");
printf("              PRODUCTION   SALES\n");
printf("              -----------  ---- \n");
for(i=1;i<=4;i++)
{
printf(" Week(%d)\t",i);
printf("%7d\t%7d\n",Mweek[i],Sweek[i]);
}
break;
case 3: 
printf("PRODUCT WISE TOTAL PROCUTION & SALES\n\n");
printf("                   PRODUCTION  SALES\n");
printf("                   ----------  ---- \n");
for(j=1;j<=5;j++)
{
printf(" Product(%d)\t",j);
printf("%7d\t%7d\n",Mproduct[j],Sproduct[j]);
}
break;
case 4:
printf(" GRAND TOTAL OF PRODUCTION & SALES\n");
printf("\n Total production = %d\n",Mtotal);
printf(" Total sales = %d\n",Stotal);
break;
default:
printf("Wrong choice, select again\n\n");
break;
}
}
printf("Exit from the program\n\n");
getch();
}
OUTPUT
Enter products manufactured week_wise
M11,M12,----,M21,M22, ----etc
11 15 12 14 13
13 13 14 15 12
12 16 10 15 14
14 11 15 13 12
Enter products sold week_wise
S11,S12,----,S21,S22,---- etc
10 13 9   12 11
12 10 12 14 10
11 14 10 14 12
12 10 13 11 10
Enter cost of each product
10 20 30 15 25

Following is the list of things you can
request for. Enter appropriate item number
and press RETURN key
1.Value matrices of production & sales
2.Total value of weekly production & sales
3.Product_wise monthly value of product  & sales
4.Grand total value of production & sales
5.Exit
ENTER YOU CHOISE: 1
VALUE MATRIX OF PRODUCTION
Week(1)     110  300  360  210  325
Week(2)     130  260  420  225  300
Week(3)     120  320  300  225  350
Week(4)     140  220  450  185  300
VALUE MATRIX OF SALES
Week(1)     100  260  270  180  275
Week(2)     120  200  360  210  300
Week(3)     110  280  300  210  300
Week(4)     120  200  390  165  250
ENTER YOUR CHOISE: 2
TOTAL WEEKLY PRODUCTION & SALES
                               PRODUCTOIN     SALES
Week(1)                         1305                1085
Week(2)                         1335                1140
Week(3)                         1315                1200
Week(4)                         1305                1125
ENTER YOU CHOISE: 3
PRODUCT_WISE TOTAL PRODUCTION & SALES
                                            PRODUCTION     SALES    
Product(1)                                  500                   450
Product(2)                                1100                   940
Product(3)                                1530                 1320
Product(4)                                  855                   765
Product(5)                                1275                 1075
ENTER YOU CHOISE: 4
GRAND TOTAL OF PRODUCTION & SALES
Total production    = 5260
Total sales        = 4550
ENTER YOUR CHOISE: 5
G O O D  B Y E
Exit from the program

Arrays

Evaluating a Test

#include <stdio.h>
#define STUDENT 3
#define ITEMS 25
void main()
{
char key[ITEMS+1],response[ITEMS+1];
int count,i,student,n,correct[ITEMS+1];
clrscr();
printf("Input key to the items\n");
for(i=0;i<ITEMS;i++)
scanf("%c",&key[i]);
scanf("%c",&key[i]);
key[i]='\0';
for(student=1;student<=STUDENT;student++)
{
count=0;
printf("\n");
printf("Input responses of student-%d\n",student);
for(i=0;i<ITEMS;i++)
scanf("%c",&response[i]);
scanf("%c",&response[i]);
response[i]='\0';
for(i=0;i<ITEMS;i++)
correct[i]=0;
for(i=0;i<ITEMS;i++)
if(response[i]==key[i])
{
count=count+1;
correct[i]=1;
}
printf("Student-%d\n",student);
printf("Score is %d Out of %d\n",count,ITEMS);
printf("Response to the items below are wrong\n");
n=0;
for(i=0;i<ITEMS;i++)
if(correct[i]==0)
{
printf("%d ",i+1);
n++;
}
if(n==0)
printf("NIL\n");
printf("\n");
}
getch();
}

Arrays

Calculation of Standard Deviation

#include <stdio.h>
#include <math.h>
#define MAXSIZE 100
void main()
{
int i,n;
float value[MAXSIZE],deviation,sum,sumsqr,mean,variance,stddeviation;
sum=sumsqr=n=0;
printf("Input vaues: input -1 to end\n");
for(i=1;i<MAXSIZE;i++)
{
scanf("%f",&value[i]);
if(value[i]==-1)
break;
sum+=value[i];
n+=1;
}
mean=sum/(float)n;
for(i=1;i<=n;i++)
{
deviation = value[i]-mean;
sumsqr+=deviation*deviation;
}
variance = sumsqr/(float)n;
stddeviation=sqrt(variance);
printf("\nNumber of items: %d\n",n);
printf("Mean : %f\n",mean);
printf("Standard deviation : %f\n",stddeviation);
getch();
}

Arrays

Median of a List of Numbers

#include <stdio.h>
#define N 10
void main()
{
int i,j,n;
float median,a[N],t;
clrscr();
printf("Enter the number of items\n");
scanf("%d",&n);
printf("Input %d values \n",n);
for(i=1;i<=n;i++)
scanf("%f",&a[i]);
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{
if(a[j]<=a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
else
continue;
}
}
if(n%2==0)
median = (a[n/2] + a[n/2+1])/2.0;
else
median = a[n/2+1];
for(i=1;i<=n;i++)
printf("%f ",a[i]);
printf("\n\nMedian is %f\n",median);
getch();
}

Arrays

A survey to know the popularity of four cars (Ambassador, Fiat, Dolphin and Maruti) was conducted in four cities (Bombay, Calcutta, Delhi and Madras). Each person surveyed was asked to give his city and the type of car he was using. The results, in coded form, are tabulated as follows:
M 1 C 2 B 1 D 3 M 2 B 4
C 1 D 3 M 4 B 2 D 1 C 3
D 4 D 4 M 1 M 1 B 3 B 3
D1 C 2 B 3 M 1 B 1 C 2
D 3 M 4 C 1 D 2 M 3 B 4
Codes represent the following information:
M - Madras  1 - Ambassador
D - Delhi       2 - Fiat
C - Calcutta  3 - Dolphin
B - Bombay  4 - Maruti
Write a program to produce a table showing popularity of various cars in four cities.

#include <stdio.h>
void main()
   {
       int  i, j, car;
       int  frequency[5][5] = { {0},{0},{0},{0},{0} };
       char city;
       printf("For each person, enter the city code \n");
       printf("followed by the car code.\n");
       printf("Enter the letter X to indicate end.\n");
   /*. . . . . . TABULATION BEGINS  . . . . . */
       for( i = 1 ; i < 100 ; i++ )
       {
   scanf("%c", &city );
   if( city == 'X' )
     break;
   scanf("%d", &car );
   switch(city)
   {
     case 'B' :  frequency[1][car]++;
       break;
  case 'C' :  frequency[2][car]++;
       break;
  case 'D' :  frequency[3][car]++;
       break;
  case 'M' :  frequency[4][car]++;
       break;
   }
       }
/*. . . . .TABULATION COMPLETED AND PRINTING BEGINS. . . .*/
       printf("\n\n");
       printf("              POPULARITY  TABLE\n\n");
       printf("-------------------------------------------\n");
       printf("City     Ambassador  Fiat  Dolphin  Maruti \n");
       printf("-------------------------------------------\n");
       for( i = 1 ; i <= 4 ; i++ )
       {

     switch(i)
   {
  case 1 :  printf("Bombay    ") ;
     break ;
  case 2 :  printf("Calcutta  ") ;
     break ;
  case 3 :  printf("Delhi     ") ;
     break ;
  case 4 :  printf("Madras    ") ;
     break ;
   }
   for( j = 1 ; j <= 4 ; j++ )
      printf("%7d", frequency[i][j] ) ;
   printf("\n") ;
       }
       printf("-------------------------------------------\n");
    /*. . . . . . . . . PRINTING ENDS. . . . . . . . . . .*/
       getch();
   }

Arrays

Write a program to compute and print a multiplication table for numbers 1 to 5.

#include <stdio.h>
#define    ROWS     5
#define    COLUMNS  5
void main()
   {   int   row, column, product[ROWS][COLUMNS] ;
       int   i, j ;
       printf("   MULTIPLICATION TABLE\n\n") ;
       printf("    ") ;
       for( j = 1 ; j <= COLUMNS ; j++ )
  printf("%4d" , j ) ;
       printf("\n") ;
       printf("-------------------------\n");
       for( i = 0 ; i < ROWS ; i++ )
       {   row = i + 1 ;
    printf("%2d |", row) ;
    for( j = 1 ; j <= COLUMNS ; j++ )
    {  column = j ;
       product[i][j] = row * column ;
       printf("%4d", product[i][j] ) ;
    }
    printf("\n") ;
       }
       getch();
   }

Array

Write a program using a two-dimensional array to compute and print the following information from the table:
(a) Total value of sales by each girl.
(b) Total value of each item sold.
(c) Grand total of sales of all items by all girls.

#include <stdio.h>
#define     MAXGIRLS     4
#define     MAXITEMS     3
void main()
   {
       int   value[MAXGIRLS][MAXITEMS];
       int   girl_total[MAXGIRLS] , item_total[MAXITEMS];
       int   i, j, grand_total;
   /*.......READING OF VALUES AND COMPUTING girl_total ...*/
       printf("Input data\n");
       printf("Enter values, one at a time, row-wise\n\n");
       for( i = 0 ; i < MAXGIRLS ; i++ )
       {
   girl_total[i] = 0;
   for( j = 0 ; j < MAXITEMS ; j++ )
   {
      scanf("%d", &value[i][j]);
      girl_total[i] = girl_total[i] + value[i][j];
   }
       }
  /*.......COMPUTING item_total..........................*/
       for( j = 0 ; j < MAXITEMS ; j++ )
       {
   item_total[j] = 0;
   for( i =0 ; i < MAXGIRLS ; i++ )
      item_total[j] = item_total[j] + value[i][j];
       }

/*.......COMPUTING grand_total.........................*/
       grand_total = 0;
       for( i =0 ; i < MAXGIRLS ; i++ )
   grand_total = grand_total + girl_total[i];
/* .......PRINTING OF RESULTS...........................*/
       printf("\n GIRLS TOTALS\n\n");
       for( i = 0 ; i < MAXGIRLS ; i++ )
   printf("Salesgirl[%d] = %d\n", i+1, girl_total[i] );
       printf("\n ITEM  TOTALS\n\n");
       for( j = 0 ; j < MAXITEMS ; j++ )
   printf("Item[%d] = %d\n", j+1 , item_total[j] );
       printf("\nGrand Total = %d\n", grand_total);
       getch();
   }

Arrays

Given below is the list of marks obtained by a class of 50 students in an annual examination.
43 65 51 27 79 11 56 61 52 09 25 36 07 49 55 63 74 81 49 37
40 49 16 75 87 91 33 24 58 78 65 56 76 67 45 54 35 63 12 21
73 49 51 19 39 49 68 93 85 59
Write a program to count the number of students belonging to each of following groups of marks: 0-9, 10-19, 20-29 .....100.

#include <stdio.h>
#define   MAXVAL    50
#define   COUNTER   11
void main()
   {
       float        value[MAXVAL];
       int          i, low, high;
       int   group[COUNTER] = {0,0,0,0,0,0,0,0,0,0,0};
  /* . . . . . . . .READING AND COUNTING . . . .  . .*/
       for( i = 0 ; i < MAXVAL ; i++ )
       {
/*. . . . . . . .READING OF VALUES . . . . . . . . */
   scanf("%f", &value[i]) ;
 /*. . . . . .COUNTING FREQUENCY OF GROUPS. . . . . */
   ++ group[ (int) ( value[i] + 0.5 ) / 10] ;
       }
 /* . . . .PRINTING OF FREQUENCY TABLE . . . . . . .*/
       printf("\n");
       printf(" GROUP     RANGE     FREQUENCY\n\n") ;
       for( i = 0 ; i < COUNTER ; i++ )
       {
   low  = i * 10 ;
   if(i == 10)
     high = 100 ;
   else
     high = low + 9 ;
   printf("  %2d    %3d to %3d       %d\n",
    i+1, low, high, group[i] ) ;
       }
       getch();
   }

Arrays

Writ a program that uses a one-dimensional array x to read the values and compute the sum of their of their squares.

#include <stdio.h>
void main()
{
int i;
float x[10],value,total;
printf("ENTER 10 REAL NUMBERS\n");
for(i=0;i<10;i++)
{
scanf("%f",&value);
x[i]=value;
}
total=0.0;
for(i=0;i<10;i++)
total=total+x[i]*x[i];
printf("\n");
for(i=0;i<10;i++)
printf("x[%2d]=%5.2f\n",i+1,x[i]);
printf("\ntotal = %.2f\n",total);
getch();
}

Thursday, February 24, 2011

Decision Making and Looping

Given a set of 10 two-digit integers containing both positive and negative values, write a program using for loop to compute the sum of all positive values and print the sum and the number of values added. The program should use scanf to read the values and terminate when the sum exceeds 999. Do not use goto statement.


#include <stdio.h>
void main()
{
int x,i,sum=0,count=0;
clrscr();
printf("Enter 10 two-digit integer number\n");
for(i=1;i<=10;i++)
{
scanf("%d",&x);
if(x>0)
{
count++;
sum+=x;
if(sum>999)
break;
}
}
printf("%d numbers are added and result = %d",count,sum);
getch();
}

Decision Making and Looping

Write a program to print 
S  S  S  S  S
S  S  S  S  S
S  S  O S  S
S  S  S  S  S
S  S  S  S  S


#include <stdio.h>

void main()
{
int row,column;
clrscr();
putchar('\n');
for(row=1;row<=5;row++)
{
for(column=1;column<=5;column++)
{
if(row==3&&column==3)
printf(" 0");
else
printf(" S");
}
putchar('\n');
}
getch();
}

Decision Making and Looping

Write a program to print all integers that are no divisible by either 2 or 3 and lie between 1 and 100. Program should also account the number of such integers and print the result.


#include <stdio.h>

void main()
{
int i,count=0;
clrscr();
for(i=0;i<=100;i++)
{
if(i%2!=0||i%3!=0)
{
count++;
printf("%d ",i);
}
}
printf("\nTotal Numbers = %d",count);
getch();
}

Decision Making and Looping

Write a program to print a square of size 5 by using the character S as shown below:
(a) S  S  S  S  S                (b) S  S  S  S  S
     S  S  S  S  S                      S               S
     S  S  S  S  S                      S               S
     S  S  S  S  S                      S               S
     S  S  S  S  S                      S  S  S  S  S


#include <stdio.h>

void main()
{
int row,column;
clrscr();
for(row=1;row<=5;row++)
{
for(column=1;column<=5;column++)
printf("S");
putchar('\n');
}
printf("\n\n");
for(row=1;row<=5;row++)
{
for(column=1;column<=5;column++)
{
if(row>1&&row<5&&column>1&&column<5)
printf(" ");
else
printf("S");
}
putchar('\n');
}
getch();
}



Decision Making and Looping

Write a program using for and if statement to display the capital letter S in a grid of 15 rows and 18 columns as shown below.
* * * * * * * * * * * * * * * * * *
* *- - - - - - - - - - - - - - - - - - - * *
* * * * * * * * * - - - - - - - - - * *  
* * * *
* * * *
* * * *
* * * * * - - - - - - - - - - - -* * * *
- - - - - - - - - - - - - - - - -- -* * * * 
- - - - - - - - - - - - - - - - - - * * * * 
                                        * * * *
                                        * * * *
                                        * * * *
* * * * - - - - - - - - - - - ---* * * *
* * * - - - - - - - - - - - - - - * * * *
* * - - - - - - - - - - - - - - - * * * * 


#include <stdio.h>

void main()
{
int row,column;
clrscr();
for(row=1;row<=15;row++)
{
for(column=1;column<=18;column++)
{
if(row==2&&column>2&&column<16)
printf("-");
else
if(row==3&&column>9&&column<16)
printf("-");
else
if(row>3&&row<7&&column>4)
printf(" ");
else
if(row==7&&column>5&&column<14)
printf("-");
else
if(row>7&&row<10&&column<14)
printf("-");
else
if(row>9&&row<13&&column<14)
printf(" ");
else
if(row==13&&column>4&&column<14)
printf("-");
else
if(row==15&&column>2&&column<14)
printf("-");
else
printf("*");
}
putchar('\n');
}
getch();
}

Decision Making and Looping

Write a program that will read a positive integer and determine and print its binary equivalent.
(Hint: The bits of the binary representation of an integer can be generated by repeatedly dividing the number and the successive quotients by 2 and saving the remainder, which is either 0 or 1, after each division.)

#include <stdio.h>

void main()
{
int num,i;
clrscr();
printf("Enter the no. to be printed in binary:");
scanf("%d",&num);
while(num!=0)
{
printf("%d",num%2);
num=num/2;
}
getch();
}

Decision Making and Looping

Write a program to print a table of values of the function 
y = exp(-x)
for x varying from 0.0 to 10.0 in steps of 0.10. The table should appear as follows:


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

void main()
{
float x,y,i;
clrscr();
printf("                      TABLE OF X= EXP(-X)\n\n");
printf("X");
for(i=0.1;i<=1.0;i+=0.1)
printf("   %1.1f ",i);
printf("\n");
for(x=0.0;x<=9.0;x=x+1.0)
{
printf("%2.1f",x);
for(i=0.1;i<=1.0;i=i+0.1)
{
y=exp(-(x+i));
printf(" %1.4f",y);
}
printf("\n");
}
getch();
}

Decision Making and Looping

Write a programs to read the age of 100 persons and count the number of persons in the age group 50 to 60. Use for and continue statements.


#include <stdio.h>

void main()
{
int n=0,age,count=0;
clrscr();
printf("Enter the age of persons to goto end type 999:");
for(;n<=100;n++)
{
scanf("%d",&age);
if(age==999)
break;
if(age>50&&age<60)
{
count=count+1;
continue;
}
}
printf("Age above 50 and below 60: %d",count);
getch();
}

Decision Making and Looping

Write a program to print the following outputs using for loops.
(a) 1                            (b) * * * * *
      2 2                              * * * *
      3 3 3                           * * *
      4 4 4 4                        * *
      5 5 5 5 5                     *

#include <stdio.h>
void main()
{
int x,i;
clrscr();
for(i=1;i<=5;i++)
{
for(x=1;x<=i;x++)
{
printf("%d",i);
}
putchar('\n');
}
putchar('\n');
for(i=5;i>=1;i--)
{
for(x=i;x>=1;x--)
{
putchar('*');
}
putchar('\n');
}
getch();
}

Decision Making and Looping

Rewrite the program of the reverse the digits of the number using the for statement.

#include <stdio.h>
#include <math.h>
void main()
{
int x,y,i=0,ans,P,n;
clrscr();
printf("Enter a number and number of digits:");
scanf("%d %d",&x,&n);
for(;i<n;i++)
{
y=pow(10,i);
P=x/y;
ans=P%10;
printf("%d",ans);
}
getch();
}

Wednesday, February 23, 2011

Decision Making and Looping

The numbers in the sequence
1 1 2 3 5 8 13 21 ........
are called Fibonacci numbers. Write a program using a do....while loop to calculate and print the first m Fibonacci numbers.
(Hint: After the first two numbers in the series, each number is the sum of the two preceding numbers.)

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


Decision Making and Looping

Write a program to compute the sum of the digits of a given integer number.

#include <stdio.h>
#include <math.h>
void main()
{
unsigned int x,y,i=0,ans,P,n,total=0;
clrscr();
printf("Enter a number and number of digits:");
scanf("%u %u",&x,&n);
while(i<n)
{
y=pow(10,i);
P=x/y;
ans=p%10;
total=total+ans;
i++;
}
printf("%u",total);
getch();
}

Decision Making and Looping

The factorial of an integer m is the product of consecutive integers from 1 to m. That is,
factorial m = m! = m*(m-1)*.....*1.
Write a program that computes and prints a table of factroials for any given m.

#include <stdio.h>
void main()
{
int x,fact=1,i;
clrscr();
printf("Enter a number to get factorial:");
scanf("%d",&x);
for(i=x;i>=1;i--)
{
fact=fact*i;
}
printf("\nFactorial = %d",fact);
getch();
}

Decision Making and Looping

Given a number, write a program using while loop to reverse the digits of the number. For example, the number 12345 should be written as 54321
(Hint: Use modulus operator to extract the last digit and the integer division by 10 to get the n-1 digit number from the n digit number.)

#include <stdio.h>
#include <math.h>
void main()
{
int x,y,i=0,ans,P,n;
clrscr();
printf("Enter a number and number of digits:");
scanf("%d %d",&x,&n);
while(i<n)
{
y=pow(10,i);
P=x/y;
ans=P%10;
printf("%d",ans);
i++;
}
getch();
}

Decision Making and Looping

Plotting of Two Functions
Problem: We have two functions of the type
y1 = exp(-ax)
y2 = exp(-a*x*x/2)
Plot the graphs of these functions for x varying from 0 to 5.0

#include <stdio.h>
#include <math.h>
void main()
{
int i;
float a,x,y1,y2;
a=0.4;
clrscr();
printf("                      Y ---->                       \n");
printf("0 ----------------------------------------------------\n");
for(x=0;x<5;x=x+0.25)
{
y1=(int)(50*exp(-a*x)+0.5);
y2=(int)(50*exp(-a*x*x/2)+0.5);
if(y1==y2)
{
if(x==2.5)
printf("X |");
else
printf(" |");
for(i=1;i<=y1-1;++i)
printf(" ");
printf(" #\n");
continue;
}
if(y1>y2)
{
if(x==2.5)
printf("X|");
else
printf(" |");
for(i=1;i<=y2-1;++i)
printf(" ");
printf("*");
for(i=1;i<=(y1-y2-1);++i)
printf("-");
printf("0\n");
continue;
}
if(x==2.5)
printf("X|");
else
printf(" |");
for(i=1;i<=(y1-1);++i)
printf(" ");
printf("0");
for(i=1;i<=(y2-y1-1);++i)
printf("-");
printf("*\n");
}
printf(" |\n");
getch();
}

Decision Making and Looping

Program to calculate Minimum Cost

#include <stdio.h>
void main()
{
float p,cost,p1,cost1;
for(p=0;p<=10;p=p+0.1)
{
cost=40-8*p+p*p;
if(p==0)
{
cost1=cost;
continue;
}
if(cost>=cost1)
break;
cost1=cost;
p1=p;
}
p=(p+p1)/2.0;
cost=40-8*p+p*p;
printf("\nMINIMUM COST = %.2f AT p = %.1f\n",cost,p);
getch();
}

Decision Making and Looping

Table of Binomial Coefficients

#include <stdio.h>
#define MAX 10
void main()
{
int m,x,binom;
clrscr();
printf("mx");
for(m=0;m<=10;++m)
printf("%4d",m);
printf("\n----------------------------------------------\n");
m=0;
do
{
printf("%2d ",m);
x=0;
binom=1;
while(x<=m)
{
if(m==0||x==0)
printf("%4d",binom);
else
{
binom=binom*(m-x+1)/x;
printf("%4d",binom);
}
x=x+1;
}
printf("\n");
m=m+1;
}
while(m<=MAX);
printf("-----------------------------------------------\n");
getch();
}

Decision Making and Looping

The program illustrates the use of continue statements,
The program evaluates the square root of a series of numbers and prints the results. The process stops when the number 9999 is typed in. In case, the series contains the negative numbers, the process of evaluation of square root should be bypassed for such numbers because the square root of a negative number is not defined. The continute statement is used to achieve this. The program also prints a message saying that the number is negative and keeps an account of negative numbers. The fineal output includes the number of positive values evaluated and the number of negative items encountered.

#include <stdio.h>
#include <math.h>
void main()
   {
       int count, negative;
       double number, sqroot;
       printf("Enter 9999 to STOP\n");
       count = 0 ;
       negative = 0 ;
       while (count <= 100)
       {
    printf("Enter a number : ");
    scanf("%lf", &number);
    if (number == 9999)
       break;     /* EXIT FROM THE LOOP */
    if (number < 0)
    {
       printf("Number is negative\n\n");
       negative++ ;
       continue;  /* SKIP REST OF THE LOOP */
    }
    sqroot = sqrt(number);
    printf("Number      = %lf\nSquare root = %lf\n\n",number, sqroot);
    count++ ;
       }
       printf("Number of items done = %d\n", count);
       printf("\n\nNegative items       = %d\n", negative);
       printf("END OF DATA\n");
       getch();
   }

Decision Making and Looping

A program to evaluate the series
1/(1-x) = 1 + x + x to power 2 + x to power 3 + ..... + x to power n

#include <stdio.h>
#define   LOOP       100
#define   ACCURACY   0.0001
void main()
   {                                                              
       int n;                                                     
       float x, term, sum;                                        
                                                              
       printf("Input value of x : ");                              
       scanf("%f", &x);                                       
       sum = 0 ;                                              
       for (term = 1, n = 1 ; n <= LOOP ; ++n)
       {                                                          
           sum += term ;                                      
    if (term <= ACCURACY)
              goto output; /* EXIT FROM THE LOOP */               
           term *= x ;                                        
       }                                                      
       printf("\nFINAL VALUE OF N IS NOT SUFFICIENT\n");            
       printf("TO ACHIEVE DESIRED ACCURACY\n");                   
       goto end;                                                  
       output:                                                    
       printf("\nEXIT FROM LOOP\n");                                
       printf("Sum = %f;  No.of terms = %d\n", sum, n);            
       end:                                                       
       ;       /* Null Statement */                                                   
       getch();
   }

Decision Making and Looping

The program reads a list of positive values and calculates their average. The for loop is written to read 1000 values. However, if we want the program to calculate the average of any set of values less than 1000, then we must enter a 'negative' number after the last value in the list, to mark the end of input.

#include <stdio.h>
void main()
   {
       int m;
       float x, sum, average;
       printf("This program computes the average of a set of numbers\n");
       printf("Enter values one after another\n");
       printf("Enter a NEGATIVE number at the end.\n\n");
       sum = 0;
       for (m = 1 ; m <= 1000 ; ++m)
       {
    scanf("%f", &x);
    if (x < 0)
       break;
    sum += x ;
       }
       average = sum/(float)(m-1);
       printf("\n");
       printf("Number of values = %d\n", m-1);
       printf("Sum              = %f\n", sum);
       printf("Average          = %f\n", average);
       getch();
   }

Decision Making and Looping

A class of n students take an annual examination in m subjects. A program to read the marks obtained by each student in various subjects and to compute and print the total marks obtained by each of them is given.

#include <stdio.h>
#define FIRST   360
#define SECOND  240
void main()
   {
       int n, m, i, j,
    roll_number, marks, total;
       printf("Enter number of students and subjects\n");
       scanf("%d %d", &n, &m);
       printf("\n");
       for (i = 1; i <= n ; ++i)
       {
    printf("Enter roll_number : ");
    scanf("%d", &roll_number);
    total = 0 ;
printf("\nEnter marks of %d subjects for ROLL NO %d\n",
m,roll_number);
    for (j = 1; j <= m; j++)
    {
        scanf("%d", &marks);
        total = total + marks;
    }
    printf("TOTAL MARKS = %d ", total);
    if (total >= FIRST)
        printf("( First Division )\n\n");
    else if (total >= SECOND)
     printf("( Second Division )\n\n");
  else
     printf("( ***  F A I L  *** )\n\n");
       }
       getch();
   }

Decision Making and Looping

The program uses a for loop to print the "Powers of 2" table for the power 0 to 20. both positive and negative.

#include <stdio.h>
void main()
   {
       long int p;
       int      n;
       double   q;
       printf("------------------------------------------\n");
       printf(" 2 to power n       n       2 to power -n\n");
       printf("------------------------------------------\n");
       p = 1;
       for (n = 0; n < 21 ; ++n)    /* LOOP BEGINS */
       {
    if (n == 0)
       p = 1;
    else
       p = p * 2;
    q = 1.0/(double)p ;
    printf("%10ld %10d %20.12lf\n", p, n, q);
       }                           /* LOOP ENDS   */
       printf("------------------------------------------\n");
       getch();
   }

Decision Making and Looping

A program to print the multiplication table from 1x1 to 12x10 as shown below is given
1  2  3  4  .......  10
2  4  6  8  .......  20
-
-
12            ....... 120

#include <stdio.h>
#define COLMAX 10
#define ROWMAX 12
void main()
   {
       int row,column, y;
       row = 1;
       printf("          MULTIPLICATION TABLE           \n");
       printf("-----------------------------------------\n");
       do    /*......OUTER LOOP BEGINS........*/
       {
     column = 1;
     do   /*.......INNER LOOP BEGINS.......*/
     {
   y = row * column;
   printf("%4d", y);
   column = column + 1;
     }
     while (column <= COLMAX); /*... INNER LOOP ENDS ...*/
     printf("\n");
     row = row + 1;
       }
       while (row <= ROWMAX);/*.....   OUTER LOOP ENDS   .....*/
       printf("-----------------------------------------\n");
       getch();
   }

 

Decision Making and Looping

A program to evaluate the equation 
y = x raised to n power
when n is a non-negative integer, is given.

#include <stdio.h>
void main()
{
int count,n;
float x,y;
printf("Enter the values of x and n:");
scanf("%f %d",&x,&n);
y=1.0;
count=1;
while(count<=n)
{
y=y*x;
count++;
}
printf("\nx = %f; n = %d; x to power n = %f\n",x,n,y);
getch();
}

Thursday, February 17, 2011

Decision Making and Branching

Write a program to read a double-type value x that represents angle in radians and a character-type variable T that represents the type of trigonometric function and display the value of
(a) sin(x), if s or S is assigned to T,
(b) cos(x), if c or C is assigned to T, and
(c) tan(x), if t or T is assigned to T
using if.......else statement

#include <stdio.h>
#include <math.h>
void main()
{
float x,result;
char T;
clrscr();
printf("Enter the trignometric function\nS for sin,C for cos and T for tan\n and its angle:");
scanf("%c %f",&T,&x);
if(T=='s'||T=='S')
{
result= sin(x);
printf("Result = %f",result);
}
else
if(T=='c'||T=='C')
{
result=cos(x);
printf("Result = %f",result);
}
else
if(T=='t'||T=='T')
{
result=tan(x);
printf("Result = %f",result);
}
else
printf("Wrong Input");
getch();
}

Decision Making and Branching

Write a program to compute and display the sum of all integers that are divisible by 6 but not divisible by 4 and lie between 0 and 100. The program should also count and display the number of such values.

#include <stdio.h>
void main()

{
int i,count=0,sum=0;
clrscr();
for(i=0;i<=100;i++)
{
if(i%6==0&&i%4!=0)
{
count++;
sum=sum+i;
}
}
printf("Sum = %d\nTotal number = %d",sum,count);
getch();
}

Decision Making and Branching

An electricity board charges the following rates for the use of electricity:
For the First 200 units: 80 P per unit
For the Next 100 units: 90 P per unit
Beyond 300 units: Rs. 1.00 per unit
All users are charged a minimum of Rs. 100 as meter charge. If the total amount is more than Rs. 400, then an additional surcharge of 15% of total amount is charged. Write a program to read the names of users and number of units consumed and print out the charges with names.

#include <stdio.h>
void main()

{
char name[10];
float unit, charge;
clrscr();
printf("Enter your name and unit Consumed:");
scanf("%s %f",&name,&unit);
if(unit<125)
charge=100;
else if(unit<=200)
charge=unit*.80;
else if(unit<=300)
charge=(unit-200)*0.90+160;
else
if(unit>300)
charge=(unit-300)*1+250;
if(charge>=400)
charge=charge+charge*0.15;
printf("Name: %s\nCharge: %5.2f",name,charge);
getch();
}