SlideShare a Scribd company logo
1 of 87
Write a program to copy the contents of one array into
another in the reverse order.
Source Code :
#include<stdio.h>
void main()
{
int a[10],b[10],i,j;
clrscr();
printf("nEnter Elements : ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0,j=9;i<10;i++,j--)
{
b[i]=a[j];
}
printf("nArray after Copying in Reverse Order : ");
for(i=0;i<10;i++)
{
printf("%d ",b[i]);
}
getch();
}
Output :
Enter Elements : 2 6 3 5 9 8 7 4 1 0
Array after Copying in Reverse Order : 0 1 4 7 8 9 5 3 6 2
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n=10,a[20],b[20];
clrscr();
printf("How many element do you wish to enter in array? :"); scanf("%d",&n);
printf("nEnter the Elements:n");
for(i=0;i<n;i++)
{
printf("Enter Element No %d : ",1+i);
scanf("%d",&a[i]);
}
printf("n Original ARRAY: n");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
for(i=0;i<n;i++)
{
b[n-1-i]=a[i];
}
printf("n Copied ARRAY: n");
for(i=0;i<n;i++)
printf(" %d ",b[i]);
getch();
}
//***********************
//www.botskool.com
//***********************
Program to print array element in reverse order.
Code for Program to print array element in reverse order in C Programming
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,i,n;
clrscr();
printf("Enter the no of elements:");
scanf("%d",&n);
ptr=(int *)malloc(sizeof(int)*n);
if(ptr==NULL)
{
printf("Not enough memory");
exit(1);
}
for(i=0; i<n; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&ptr[i]);
}
printf("Array in original ordern");
for(i=0; i<n; i++)
{
printf("%dn",ptr[i]);
}
printf("Array in reverse ordern");
for(i=n-1; i>=0; i--)
{
printf("%dn",ptr[i]);
}
getch();
return 0;
}
void reverse( int array[], int length)
{
int ii, temp;
int jj = 0;
int *tempArray = (int)malloc( length * sizeof( int));
for ( ii = length-1; ii >= 0; ii--)
{
tempArray[jj] = array[ii];
jj += 1;
}
array = *tempArray;
for (ii = 0; ii <= length-1; ii++)
{
printf("DEBUGn");
temp = tempArray[ii];
array[ii] = temp;
}
free( tempArray);
}
#include<stdio.h>
#include<conio.h>
voidmain()
{
int i,j,a[100],b[100];
printf("How many numbers youwant to store:=n");
scanf("%d",&j);
printf("Enter the numbers:=n");
for(i=0;i<j;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<j;i++)
{
b[i]=a[j-i-1];
}
printf("Reversedorder:=n");
for(i=0;i<j;i++)
{
printf("%dn",b[i]);
}
getch();
}
Write a program to copy the contents of one array into another in the reverse
order.
void main()
{
int arr1[5]={1,2,3,4,5};
int arr2[5];
int i,k;
for (i=4,k=0;i>=0;i--,k++)
arr2[k]=arr1[i];
for(i=0;i<5;i++)
printf("nValue of arr2[%d] is %d",i,arr2[i]);
}
With Pointers
void main()
{
int arr1[5]={1,2,3,4,5};
int arr2[5];
int *m;
int i,*j,k,l=5;
j=arr1;
m=arr2;
func(j,m,l);
for(i=0;i<5;i++)
printf("nValue of arr2[%d] is %d",i,arr2[i]);
}
func(int *j, int *m, int l)
{
int i;
for(j=j+4,i=0;i<5;i++,j--,m++)
*m=*j;
}
#include<stdio.h>
#include<conio.h>
main()
{
int num[10];
int x;
for(x=0;x<10;x++)
{
printf("Enter number %d : ",x);
scanf("%d", &num[x]);
}
for(x=0;x<10;x++)
{
printf(" %d ",num[x]);
}
//clrscr ();
num[x]=0;
for(x=10;x>-1;x--)
{
printf(" %d ",num[x]);
}
getch();
}
C program to reverse an array: This program reverses the array elements. For example if a is
an array of integers with three elements such that
a[0] = 1
a[1] = 2
a[2] = 3
Then on reversing the array will be
a[0] = 3
a[1] = 2
a[0] = 1
Given below is the c code to reverse an array.
C programming code
#include <stdio.h>
int main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in arrayn");
scanf("%d", &n);
printf("Enter the array elementsn");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
/*
* Copying elements into array b starting from end of array a
*/
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
/*
* Copying reversed array into original.
* Here we are modifying original array, this is optional.
*/
for (c = 0; c < n; c++)
a[c] = b[c];
printf("Reverse array isn");
for (c = 0; c < n; c++)
printf("%dn", a[c]);
return 0;
}
Download Reverse array program.
Output of program:
Reverse array by swapping (without using additionalmemory)
#include <stdio.h>
int main() {
int array[100], n, c, t, end;
scanf("%d", &n);
end = n - 1;
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
for (c = 0; c < n/2; c++) {
t = array[c];
array[c] = array[end];
array[end] = t;
end--;
}
printf("Reversed array elements are:n");
for (c = 0; c < n; c++) {
printf("%dn", array[c]);
}
return 0;
}
C program to reverse an array using pointers
#include <stdio.h>
#include <stdlib.h>
void reverse_array(int*, int);
int main()
{
int n, c, *pointer;
scanf("%d",&n);
pointer = (int*)malloc(sizeof(int)*n);
if( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 0 ; c < n ; c++ )
scanf("%d",(pointer+c));
reverse_array(pointer, n);
printf("Original array on reversal isn");
for ( c = 0 ; c < n ; c++ )
printf("%dn",*(pointer+c));
free(pointer);
return 0;
}
void reverse_array(int *pointer, int n)
{
int *s, c, d;
s = (int*)malloc(sizeof(int)*n);
if( s == NULL )
exit(EXIT_FAILURE);
for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )
*(s+d) = *(pointer+c);
for ( c = 0 ; c < n ; c++ )
*(pointer+c) = *(s+c);
free(s);
}
Chap 8[D]a Search quantity of instances in Array
Twenty-five numbers are entered from the keyboard into an array. The number to
be searched is entered through the keyboard by the user. Write a program to find
if the number to be searched is present in the array and if it is present, display the
number of times it appears in the array.
void main()
{
int arr[25];
int a,d,i;
for(i=0;i<25;i++)
{
printf("nKey %d) value",i);
scanf("%d",&arr[i]);
}
printf("n25 numbers stored, enter any integer again");
scanf("%d",&d);
for(i=0,a=0;i<25;i++)
{
if(arr[i]==d)
a++;
}
if(a>0)
printf("nThe integer appeared %d times in the array",a);
else
printf("nThe integer did not appear in the array");
}
hap8[D]b Finding +tive -tive zeros, odd and even numbers in array
Twenty-five numbers are entered from the keyboard into an array. Write a
program to find out how many of them are positive, how many are negative, how
many are even and how many odd.
void main()
{
int arr[25];
int a,b,c,d,e,i;
a=0;
b=0;
c=0;
d=0;
e=0;
for(i=0;i<25;i++)
{
printf("nKey the %d) value",i);
scanf("%d",&arr[i]);
}
for(i=0;i<25;i++)
{
if(arr[i]>0)
a++;
if(arr[i]<0)
b++;
if(arr[i]==0)
c++;
if(arr[i]%2==0)
d++;
else
e++;
}
if(a>0)
printf("nThere are %d positive integers",a);
if(b>0)
printf("nThere are %d negative integers",b);
if(c>0)
printf("nThere are %d zeros",c);
if(d>0)
printf("nThere are %d even numbers",d);
if(e>0)
printf("nThere are %d odd numbers",e);
}
Chap8[D]c Selection sort
Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set
of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms) − Selection sort
− Bubble Sort − Insertion Sort
/* Selection sort */
void main()
{
int arr[25];
int a,b,d,i;
printf("nInput 25 numbers into array");
for(i=0;i<25;i++)
{
printf("nKey the %d) value",i);
scanf("%d",&arr[i]);
}
printf("nStarting selection sorting");
for(i=0;i<24;i++)
{
for(d=i+1;d<25;d++)
{
a=arr[i];
b=arr[d];
arr[i]=b;
arr[d]=a;
}
}
printf("nSelection sorting done");
for(i=0;i<25;i++)
printf("n%d) value is %d",i,arr[i]);
}
Chap8[D]c Buuuubbbble sort
Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set
of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms)− Selection sort
− Bubble Sort − Insertion Sort
/*Bubble sort*/
void main()
{
int arr[25];
int a,b,c,d,i;
printf("nInput 25 numbers into the array");
for(i=0;i<25;i++)
{
printf("nKey the %d) value",i);
scanf("%d",&arr[i]);
}
printf("nStarting bubble sort");
for(i=24;i>0;i--)
{
for(b=0,c=b+1;c <=i;b++,c ++)
{
a=arr[b];
d=arr[c];
arr[b]=d;
arr[c]=a;
}
}
printf("nBubble sort done");
for(i=0;i<25;i++)
printf("n%d value is %d",i,arr[i]);
}
Chap8[D]c Insertion sort
Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set
of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms) − Selection sort
− Bubble Sort − Insertion Sort
/*Insertion sort*/
void main()
{
int arr[25];
int a,b,c,i;
printf("nInput 25 numbers into the array");
for(i=0;i<25;i++)
{
printf("nKey in the %d) value",i);
scanf("%d",&arr[i]);
}
printf("nStarting insertion sort");
for(a=1;a<25;a++)
{
b=arr[0];
c=arr[a];
arr[0]=c;
arr[a]=b;
}
printf("nInsertion sort done");
for(i=0;i<25;i++)
printf("nThe %d) value is%d",i,arr[i]);
}
Chap8[D]d Sieve of Eratosthenes
Implement the following procedure to generate prime numbers from 1 to 100 into
a program. This procedure is called sieve of Eratosthenes.
step 1 Fill an array num[100] with numbers from 1 to 100
step 2 Starting with the second entry in the array, set all its multiples to zero.
step 3 Proceed to the next non-zero element and set all its multiples to zero.
step 4 Repeat step 3 till you have set up the multiples of all the non-zero elements
to zero
step 5 At the conclusion of step 4, all the non-zero entries left in the array would
be prime numbers, so print out these numbers.
Chap8[I]a Reversing contents and copy to another array
Write a program to copy the contents of one array into another in the reverse
order.
void main()
{
int arr1[5]={1,2,3,4,5};
int arr2[5];
int i,k;
for (i=4,k=0;i>=0;i--,k++)
arr2[k]=arr1[i];
for(i=0;i<5;i++)
printf("nValue of arr2[%d] is %d",i,arr2[i]);
}
With Pointers
void main()
{
int arr1[5]={1,2,3,4,5};
int arr2[5];
int *m;
int i,*j,k,l=5;
j=arr1;
m=arr2;
func(j,m,l);
for(i=0;i<5;i++)
printf("nValue of arr2[%d] is %d",i,arr2[i]);
}
func(int *j, int *m, int l)
{
int i;
for(j=j+4,i=0;i<5;i++,j--,m++)
*m=*j;
}
Chap8[I]b Check similar integers in array
If an array arr contains n elements, then write a program to check if arr[0] =
arr[n-1], arr[1] = arr[n-2] and so on.
This program will have repeated results if the input contains more than 2 same integers
void main()
{
int arr[25];
int i,*j,k;
j=arr;
printf("nInput 25 integers");
for(i=0;i<25;i++,j++)
{
printf("nKey in the %d) value",i+1);
scanf("%d",&*j);
}
for(i=0;i<25;i++)
{
for(k=24;k>i;k--)
if(arr[i]==arr[k])
printf("nArray [%d] = Array[%d]",i,k);
}
}
Chap8[I]c Finding smallest number in array using pointers
Find the smallest number in an array using pointers.
Chap8[L]a Initialising 3D array
How will you initialize a three-dimensional array threed[3][2][3]? How will you
refer the first and last element in this array?
void main()
{
int threed[3][2][3]={
{
1,2,3,
4,5,6
},
{
7,8,9,
10,11,12
},
{
13,14,15,
16,17,18
}
};
printf("nFirst element of array is %dnLast element of the array is
%d",threed[0][0][0],threed[2][1][2]);
}
hap8[L]b Pick largest number from matrix
Write a program to pick up the largest number from any 5 row by 5 column matrix.
Write a program to obtain transpose of a 4 x 4 matrix. The transpose of a matrix is
obtained by exchanging the elements of each row with the elements of the
corresponding column.
void main()
{
int arr[4][4];
int i,j,a,b,f;
printf("nInput numbers to 4*4 matrix");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("nKey in the [%d][%d]) value",i+1,j+1);
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0,f=0;j<4;j++)
{
if(i!=j&&f==0)
continue;
a=arr[i][j];
b=arr[j][i];
arr[i][j]=b;
arr[j][i]=a;
f=1;
}
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%d ",arr[i][j]);
printf("n");
}
}
Creating your own strcat()
Creating your own strcat()
void main()
{
char source[]="Folks!";
char target[30]="Hello";
scat(target,source);
printf("nSource string = %s",source);
printf("nTarget string = %s",target);
}
scat(char *m,char *n)
{
char *p;
p=m;
while(*n!='0')
{
if(*m=='0'||m>p+6)
{
*m=*n;
n++;
}
m++;
}
*m='0';
}
Very often in fairs we come across a puzzle that contains 15 numbered square
pieces mounted on a frame. These pieces can be moved horizontally or vertically.
A possible arrangement of these pieces is shown below:
As you can see there is a blank at bottom right corner. Implement the following
procedure through a program:
Draw the boxes as shown above. Display the numbers in the above order. Allow
the user to hit any of the arrow keys (up, down, left, or right). If user hits say,
right arrow key then the piece with a number 5 should move to the right and blank
should replace the original position of 5. Similarly, if down arrow key is hit, then
13 should move down and blank should replace the original position of 13. If left
arrow key or up arrow key is hit then no action should be taken. The user would
continue hitting the arrow keys till the numbers aren’t arranged in ascending
order. Keep track of the number of moves in which the user manages to arrange
the numbers in ascending order. The user who manages it in minimum number of
moves is the one who wins. How do we tackle the arrow keys? We cannot receive
them using scanf( ) function. Arrow keys are special keys which are identified by
their ‘scan codes’. Use the following function in your program. It would return the
scan code of the arrow key being hit. Don’t worry about how this function is
written. We are going to deal with it later. The scan codes for the arrow keys are:
up arrow key – 72 down arrow key – 80 left arrow key – 75 right arrow key – 77
/* Returns scan code of the key that has been hit */
#include "dos.h"
getkey( )
{
union REGS i, o ;
while ( !kbhit( ) )
;
i.h.ah = 0 ;
int86 ( 22, &i, &o ) ;
return ( o.h.ah ) ;
}
ANS:
#include "dos.h"
void main()
{
void creategrid();
int g,c;
int arr[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0};
clrscr();
creategrid();
printarray(arr);
for(g=15,c=0;;)
{
int k,a,b,i;
k=getkey();
if(k==80)
{
if((g-4)<0) a="arr[g-4];" b="arr[g];" k="="72)">15)
continue;
a=arr[g+4];
b=arr[g];
arr[g+4]=b;
arr[g]=a;
go(g);
printf("%d",arr[g]);
go(g+4);
printf("%c%c",0,0);
go(g+4);
c++;
g+=4;
}
if(k==75)
{
if(g==3g==7g==11g==15)
continue;
a=arr[g+1];
b=arr[g];
arr[g+1]=b;
arr[g]=a;
go(g);
printf("%d",arr[g]);
go(g+1);
printf("%c%c",0,0);
go(g+1);
c++;
g+=1;
}
if(k==77)
{
if(g==0g==4g==8g==12)
continue;
a=arr[g-1];
b=arr[g];
arr[g-1]=b;
arr[g]=a;
go(g);
printf("%d",arr[g]);
go(g-1);
printf("%c%c",0,0);
go(g-1);
c++;
g-=1;
}
for(i=0;i<15;i++)
{
if(arr[i]!=i+1)
break;
if(arr[i]==(i+1)&&i==14)
{
gotoxy(6,24);
printf("nNumber of moves to complete is %d",c);
exit();
}
}
}
}
go(int g)
{
switch(g)
{
case 0:
gotoxy(8,5);
break;
case 1:
gotoxy(12,5);
break;
case 2:
gotoxy(16,5);
break;
case 3:
gotoxy(20,5);
break;
case 4:
gotoxy(8,9);
break;
case 5:
gotoxy(12,9);
break;
case 6:
gotoxy(16,9);
break;
case 7:
gotoxy(20,9);
break;
case 8:
gotoxy(8,13);
break;
case 9:
gotoxy(12,13);
break;
case 10:
gotoxy(16,13);
break;
case 11:
gotoxy(20,13);
break;
case 12:
gotoxy(8,17);
break;
case 13:
gotoxy(12,17);
break;
case 14:
gotoxy(16,17);
break;
case 15:
gotoxy(20,17);
break;
}
}
getkey()
{
union REGS i,o;
while(!kbhit())
;
i.h.ah=0;
int86(22,&i,&o);
return(o.h.ah);
}
printarray(int *m)
{
int a,b,i,j;
for(a=5,i=0;a<=17;a+=4,i++)
{
for(b=8,j=0;b<=20;b+=4,j++)
{
gotoxy(b,a);
printf("%d",*(m+(i*4)+j));
}
}
gotoxy(20,17);
printf("%c",0);
}
void creategrid()
{
int a,b;
for(a=3;a<=19;a+=4)
{
for(b=6;b<=22;b++)
{
if(b==6(b-6)%4==0)
{
if(a==3)
{
if(b==6)
{
gotoxy(6,3);
printf("%c",218);
}
else if(b==22)
{
gotoxy(22,3);
printf("%c",191);
}
else
{
gotoxy(b,3);
printf("%c",194);
}
}
else if(a==19)
{
if(b==6)
{
gotoxy(6,19);
printf("%c",192);
}
else if(b==22)
{
gotoxy(22,19);
printf("%c",217);
}
else
{
gotoxy(b,19);
printf("%c",193);
}
}
else
{
if(b==6)
{
gotoxy(6,a);
printf("%c",195);
}
else if(b==22)
{
gotoxy(22,a);
printf("%c",180);
}
else
{
gotoxy(b,a);
printf("%c",197);
}
}
}
else
{
printf("%c",196);
}
}
}
for(b=6;b<=22;b+=4)
{
for(a=4;a<=18;a++)
{
if((a-3)%4==0)
continue;
else
{
gotoxy(b,a);
printf("%c",179);
}
}
}
}
Write a function to find the norm of a matrix. The norm is defined as the square
root of the sum of squares of all elements in the matrix.
he area of a triangle can be computed
by the sine law when 2 sides of the triangle and the angle between them are
known.
Area = (1 / 2 ) ab sin ( angle )
Given the following 6 triangular pieces of land, write a program to find their area
and determine which is largest,
#include math.h (include arrows)
void main()
{
float arr[6][3];
int i,j,d;
float area,c=0;
for(i=0;i<6;i++)
{
for(j=0;j<3;j++)
{
printf("nKey in the [%d][%d] value",i+1,j+1);
scanf("%f",&arr[i][j]);
}
}
for(i=0;i<6;i++)
{
area=(1.0/2.0)*arr[i][0]*arr[i][1]*sin(arr[i][2]);
if(area>c)
{ printf("n1");
c=area;
d=i;
}
}
printf("nThe biggest plot of land is plot no. %d with area %f",d+1,c);
}
For the following set of n data points (x, y), compute the correlation coefficient r,
given by
#include math.h (include arrows)
void main()
{
float arr[11][2]={
34.22,102.43,
39.87,100.93,
41.85,97.43,
43.23,97.81,
40.06,98.32,
53.29,98.32,
53.29,100.07,
54.14,97.08,
49.12,91.59,
40.71,94.85,
55.15,94.65
};
int i,j;
float sx=0,sy=0,sx2=0,sy2=0,sxy=0,b,r;
/*calculating summation x*/
for(i=0;i<11;i++)
sx=sx+arr[i][0];
printf("nsummation x is %f",sx);
/*calculating summation y*/
for(i=0;i<11;i++)
sy=sy+arr[i][1];
printf("nsummation y is %f",sy);
/*calculating summation x2*/
for(i=0;i<11;i++)
sx2=sx2+(arr[i][0]*arr[i][0]);
printf("nsummation x2 is %f",sx2);
/*calculating summation y2*/
for(i=0;i<11;i++)
sy2=sy2+(arr[i][1]*arr[i][1]);
printf("nsummation sy2 is %f",sy2);
/*calculating summation xy*/
for(i=0;i<11;i++)
sxy=sxy+(arr[i][0]*arr[i][1]);
printf("nsummation sxy is %f",sxy);
/*calculating bottom part*/
b=(i*sx2-(sx*sx))*(i*sy2-(sy*sy));
printf("nbottom is %f",b);
/*calculating coefficient r*/
r=(sxy-(sx*sy))/(sqrt(b));
printf("n The correlation coefficient is %f",r);
}
For the following set of point given by (x, y) fit a straight line given by
y = a + bx
where,
#include math.h (include arrows)
void main()
{
float arr[10][2]={
3.0,1.5,
4.5,2.0,
5.5,3.5,
6.5,5.0,
7.5,6.0,
8.5,7.5,
8.0,9.0,
9.0,10.5,
9.5,12.0,
10.0,14.0
};
int i,j;
float sx=0,sy=0,sx2=0,sxy=0,my,mx,a,b;
/* for(i=0;i<10;i++)
{
for(j=0;j<2;j++)
{
printf("nKey in the [%d][%d] value",i+1,j+1);
scanf("%f",&arr[i][j]);
}
}
*/
/*calculating summation x*/
for(i=0;i<10;i++)
sx=sx+arr[i][0];
/*calculating summation y*/
for(i=0;i<10;i++)
sy=sy+arr[i][1];
/*calculating summation x2*/
for(i=0;i<10;i++)
sx2=sx2+(arr[i][0]*arr[i][0]);
/*calculating summation xy*/
for(i=0;i<10;i++)
sxy=sxy+(arr[i][0]*arr[i][1]);
my=sy/i;
mx=sx/i;
b=((i*sxy)-(sx*sy))/((i*sx2)-(sx*sx));
a=my-(b*mx);
printf("nThe value of a is %fnThe value of b is %f",a,b);
}
Creating your own strcat()
void main()
{
char source[]="Folks!";
char target[30]="Hello";
scat(target,source);
printf("nSource string = %s",source);
printf("nTarget string = %s",target);
}
scat(char *m,char *n)
{
char *p;
p=m;
while(*n!='0')
{
if(*m=='0'||m>p+6)
{
*m=*n;
n++;
}
m++;
}
*m='0';
}
et Us C / Chapter 8(Arrays)
Exercise [D]
(a) Twenty-five numbers are entered from the keyboard
into an array. The number to be searched is entered
through the keyboard by the user. Write a program to
find if the number to be searched is present in the array
and if it is present, display the number of times it
appears in the array.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,arr[25],prsnt=0,num;
clrscr();
printf("Please enter 25 numbers: n");
for(i=0;i<25;i++) {
scanf("%d",&arr[i]);
}
printf("nnPlease enter the number to be searched: ");
scanf("%d",&num);
for(i=0;i<25;i++) {
if(num==arr[i])
prsnt=prsnt+1;
}
if(prsnt==0) {
printf("nnNumber does not present in the array.n");
}
else {
printf("nnNumber presents in the array.n");
printf("nNumber of times it appears = %d.n",prsnt);
}
getch();
}
---------------------------------------------------------------------------------------------------------------
b) Twenty-five numbers are entered from the keyboard
into an array. Write a program to find out how many of
them are positive, how many are negative, how many are
even and how many odd.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,arr[25],tz=0,tp=0,tn=0;
clrscr();
printf("Enter numbers in the array: n");
for(i=0;i<25;i++) {
scanf("%d",&arr[i]);
if(arr[i]<0){
tn=tn+1;
}
if(arr[i]==0){
tz=tz+1;
}
if(arr[i]>0){
tp=tp+1;
}
}
printf("nnnTotal zeros = %dn",tz);
printf("Total positive numbers = %dn",tp);
printf("Total negative numbers = %dn",tn);
getch();
}
----------------------------------------------------------------------------------------------------------------
(c) Implement the Selection Sort, Bubble Sort and
Insertion sort algorithms on a set of 25 numbers. (Refer
Figure 8.11 for the logic of the algorithms)
− Selection sort
− Bubble Sort
− Insertion Sort
Solution:
----------------------------------------------------------------------------------------------------------------
(d) Implement the following procedure to generate prime
numbers from 1 to 100 into a program. This procedure is
called sieve of Eratosthenes.
step 1
Fill an array num[100] with numbers from 1 to 100
step 2
Starting with the second entry in the array, set all its
multiples to zero.
step 3
Proceed to the next non-zero element and set all its
multiples to zero.
step 4
Repeat step 3 till you have set up the multiples of all the
non-zero elements to zero
step 5
At the conclusion of step 4, all the non-zero entries left
in the array would be prime numbers, so print out these
numbers.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,a[100];
clrscr();
for(i=0;i<100;i++) {
a[i]=i+1;
}
printf("n100 numbers in the array:nn");
for(i=0;i<100;i++) {
printf("%3d ",a[i]);
}
printf("nnafter implementing eratothene's sieve:nn");
for(i=2;i<100;i++) {
for(j=2;j<a[i];j++) {
if(a[i]%j==0)
a[i]=0;
}
}
i=a[0];
for(;i<100;i++) {
printf("%3d ",a[i]);
}
printf("nnprime numbers are: nn");
for(i=a[0];i<100;i++) {
if(a[i]!=0)
printf("%3d ",a[i]);
}
getch();
}
---------------------------------------------------------------------------------------------------------------
Exercise [I]
(a) Write a program to copy the contents of one array
into another in the reverse order.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,k,a1[5],a2[5];
clrscr();
for(i=1;i<=5;i++) {
scanf("%d",&a1[i]);
}
printf("nnThe elements you enterd are:n");
for(i=1;i<=5;i++) {
printf(" %d",a1[i]);
}
printf("nnElements in reversed order:n");
for(i=5,j=1;i>=1,j<=5;i--,j++) {
k=a1[i];
a2[j]=k;
printf(" %d",a2[j]);
}
getch();
}
---------------------------------------------------------------------------------------------------------------
(b) If an array arr contains n elements, then write a
program to check if arr[0] = arr[n-1], arr[1] = arr[n-2]
and so on.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int arr[100];
int n,i,f=0;
clrscr();
printf("enter total elements of array(n): ");
scanf("%d",&n);
printf("nnenter "n" elements of array: nn");
for(i=0;i<n;i++) {
scanf("%d",&arr[i]);
}
clrscr();
for(i=0;i<n;i++) {
if(arr[i]==arr[n-(i+1)]) { /* if element is equal, according to the problem,
it will be printed */
f=f+1;
printf("element no: %d = %d ",i,arr[i]);
}
}
if(f==0)
printf("nnNo such element found.n");
getch();
}
---------------------------------------------------------------------------------------------------------------
(c) Find the smallest number in an array using pointers.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,n,*p,*s,a[100];
clrscr();
printf("enter how many numbers you want to save in array: ");
scanf("%d",&n);
printf("nnenter %d number in array:n",n);
for(i=0;i<n;i++) {
scanf("%d",&a[i]);
}
clrscr();
printf("array you entered: nn");
for(i=0;i<n;i++) {
printf("%2d ",a[i]);
}
printf("nn");
p=&a[0]; /* first pointer points 0th element */
for(i=0;i<n;i++) {
s=&a[i]; /* second pointer points every element one by one */
if(*p>*s)
/* if first is bigger than second */
*p=*s; /* first becomes second */
s++; /* second is incremented to check with other elements */
}
printf("smallest digit in array is %dn",*p);
getch();
}
----------------------------------------------------------------------------------------------------------------
(d) Write a program which performs the following tasks:
− initialize an integer array of 10 elements in main( )
− pass the entire array to a function modify( )
− in modify( ) multiply each element of array by 3
− return the control to main( ) and print the new array
elements in main( )
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,a[10]={1,2,3,4,5,6,7,8,9,10};
modify();
clrscr();
printf("array before modification: nn");
for(i=0;i<10;i++) {
printf(" %d ",a[i]);
}
modify(a); /* passing only the name of array */
printf("nnnarray after modification:nn");
for(i=0;i<10;i++) { /* printing the array in main(); */
printf(" %d ",a[i]);
}
getch();
}
modify(int b[10]) {
int c;
for(c=0;c<10;c++) {
b[c]=b[c]*3; /* multiplying each element with 3 */
}
return b[c]; /* returning the whole array to main(); */
}
----------------------------------------------------------------------------------------------------------
(e) The screen is divided into 25 rows and 80 columns.
The characters that are displayed on the screen are
stored in a special memory called VDU memory (not to be
confused with ordinary memory). Each character
displayed on the screen occupies two bytes in VDU
memory. The first of these bytes contains the ASCII value
of the character being displayed, whereas, the second
byte contains the colour in which the character is
displayed.
For example, the ASCII value of the character present on
zeroth row and zeroth column on the screen is stored at
location number 0xB8000000. Therefore the colour of
this character would be present at location number
0xB8000000 + 1. Similarly ASCII value of character in row
0, col 1 will be at location 0xB8000000+ 2, and its colour
at 0xB8000000 + 3.
With this knowledge write a program which when
executed would keep converting every capital letter on
the screen to small case letter and every small case
letter to capital letter. The procedure should stop the
moment the user hits a key from the keyboard.
This is an activity of a rampant Virus called Dancing
Dolls. (For monochrome adapter, use 0xB0000000instead
of 0xB8000000).
Solution:
_______________________________________________________________________
Exercise [L]
(a) How will you initialize a three-dimensional array
threed[3][2][3]?
How will you refer the first and last element in this
array?
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
/* initialization of a 3 dimensional array */
int threed[3][2][3]={
{
{100,2,3},
{1,2,3}
},
{
{8,5,6},
{4,5,6}
},
{
{7,8,9},
{7,8,200}
}
};
int *f,*l;
clrscr();
f=&threed[0][0][0]; /* reference to first element */
l=&threed[2][1][2]; /* reference to second element */
printf("nnfirst element = %d",*f);
printf("nnlast element = %d",*l);
getch();
}
---------------------------------------------------------------------------------------------------------------
(b) Write a program to pick up the largest number from
any 5 row by 5 column matrix.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,a[5][5];
clrscr();
printf("nType the numbers to in matrix:n");
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
scanf("%d",&a[i][j]);
}
}
clrscr();
printf("matrix you entered is:nn");
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
printf(" %2d ",a[i][j]);
}
printf("n");
}
/* finding the largest number */
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
if(a[0][0]<a[i][j]) /* if number is larger than first element */
a[0][0]=a[i][j]; /* larger number is placed as the first element */
}
}
printf("nnThe largest number in matrix is: %d",a[0][0]);
getch();
}
---------------------------------------------------------------------------------------------------------------
(c) Write a program to obtain transpose of a 4 x 4 matrix.
The transpose of a matrix is obtained by exchanging the
elements of each row with the elements of the
corresponding column.
Solution:
#include<stdio.h>
#include<conio.h>
#define MAX 4
void main() {
int i,j,a[4][4],b[4][4];
clrscr();
printf("nenter numbers in 5x5 matrix: nn");
for(i=0;i<MAX;i++) {
for(j=0;j<MAX;j++) {
scanf("%d",&a[i][j]);
}
}
clrscr();
printf("nmatrix you entered is: nn");
for(i=0;i<MAX;i++) {
for(j=0;j<MAX;j++) {
printf("%2d ",a[i][j]);
}
printf("n");
}
/* transpose of matrix */
for(i=0;i<MAX;i++) {
for(j=0;j<MAX;j++) {
b[j][i]=a[i][j];
}
}
printf("nn");
/* printing the transpose */
printf("Transpose of matrix is: nn");
for(i=0;i<MAX;i++) {
for(j=0;j<MAX;j++) {
printf("%2d ",b[i][j]);
}
printf("n");
}
getch();
}
----------------------------------------------------------------------------------------------------------------
(d) Very often in fairs we come across a puzzle that
contains 15 numbered square pieces mounted on a
frame. These pieces can be moved horizontally or
vertically. A possible arrangement of these pieces is
shown below:
1 4 15 7
8 10 2 11
14 3 6 13
12 9 5
As you can see there is a blank at bottom right corner.
Implement the following procedure through a program:
Draw the boxes as shown above. Display the numbers in
the above order. Allow the user to hit any of the arrow
keys (up, down, left, or right).
If user hits say, right arrow key then the piece with a
number 5 should move to the right and blank should
replace the original position of 5. Similarly, if down
arrow key is hit, then 13 should move down and blank
should replace the original position of 13. If left arrow
key or up arrow key is hit then no action should be
taken.
The user would continue hitting the arrow keys till the
numbers aren’t arranged in ascending order.
Keep track of the number of moves in which the user
manages to arrange the numbers in ascending order. The
user who manages it in minimum number of moves is the
one who wins.
How do we tackle the arrow keys? We cannot receive
them using scanf( ) function. Arrow keys are special keys
which are identified by their ‘scan codes’. Use the
following function in your program. It would return the
scan code of the arrow key being hit. Don’t worry about
how this function is written. We are going to deal with it
later. The scan codes for the arrow keys are:
up arrow key – 72 down arrow key – 80 left arrow key – 75
right arrow key – 77
/* Returns scan code of the key that has been hit */
#include "dos.h"
getkey( )
{
union REGS i, o ;
while ( !kbhit( ) ) ;
i.h.ah = 0 ;
int86 ( 22, &i, &o ) ;
return ( o.h.ah ) ;
}
Solution:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
/* returns scan code of the key that has been hit */
getkey()
{
union REGS i,o;
while(!kbhit() )
;
i.h.ah=0;
int86(22,&i,&o);
return(o.h.ah);
}
void main() {
int i,j,a[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0};
int temp,h,moves=0,won=0;
clrscr();
/****************************************************/
do {
/**************/
/* to move up */
/**************/
if(h==72) {
for(i=0;i<16;i++) {
if(a[i]==0){
if(a[0]==0 || a[1]==0 || a[2]==0 || a[3]==0) {
break;
}
temp=a[i];
a[i]=a[i-4];
a[i-4]=temp;
moves=moves+1;
break;
}
}
}
/****************/
/* to move left */
/****************/
if(h==75) {
for(i=0;i<16;i++) {
if(a[i]==0){
if(a[0]==0 || a[4]==0 || a[8]==0 || a[12]==0) {
break;
}
temp=a[i];
a[i]=a[i-1];
a[i-1]=temp;
moves=moves+1;
break;
}
}
}
/****************/
/* to move down */
/****************/
if(h==80) {
for(i=0;i<16;i++) {
if(a[i]==0){
if(a[12]==0 || a[13]==0 || a[14]==0 || a[15]==0) {
break;
}
temp=a[i];
a[i]=a[i+4];
a[i+4]=temp;
moves=moves+1;
break;
}
}
}
/*****************/
/* to move right */
/*****************/
if(h==77) {
for(i=0;i<16;i++) {
if(a[i]==0) {
if(a[3]==0 || a[7]==0 || a[11]==0 || a[15]==0 ) {
break;
}
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
moves=moves+1;
break;
}
}
}
/***********************************************************/
/**********************************/
/* printing the puzzle with boxes */
/**********************************/
printf("n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%cn",218,196,196,196,194,196,196,196,194,
196,196,196,194,196,196,196,191);
for(i=0;i<=15;i++) {
printf("%c",179);
if(a[i]==0) {
printf("%c ",32); /* printing a blank space in the puzzle */
}
if(a[i]!=0)
printf(" %2d",a[i]);
if(a[i]==a[3] || a[i]==a[7] || a[i]==a[11] || a[i]==a[15])
printf("%c",179);
if(i==3||i==7||i==11)
printf("n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%cn",195,196,196,196,197,196,196,196,197,
196,196,196,197,196,196,196,180);
if(a[0]==1 && a[1]==2 && a[2]==3 && a[3]==4 && a[4]==5 && a[5]==6
&&a[6]==7 && a[7]==8 && a[8]==9 && a[9]==10 && a[11]==12 && a[12]==13
&& a[13]==14 && a[14]==15 && a[15]==0 ) {
won=1;
}
}
printf("n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%cn",192,196,196,196,193,196,196,196,193,
196,196,196,193,196,196,196,217);
/***************************************************/
if(won==1) {
printf("nntCongratulations! you have won.");
break;
}
/**********************************/
/* to print instructions for user */
/**********************************/
printf("nnnnnn Total Moves: %dtttt Use arrow keys to move blank:nn",moves);
printf("tttttt %c to move upn",30);
printf("tttttt %c to move downn",31);
printf("tttttt %c to move leftn",17);
printf("tttttt %c to move rightn",16);
/****************************************************/
/**********************/
/* to take user input */
/**********************/
h=getkey();
clrscr();
/****************************************************/
}while(h==72 || h==75 || h==77 ||h==80);
getch();
}
-----------------------------------------------------------------------------------------------------------------
(e) Those readers who are from an Engineering/Science
background may try writing programs for following
problems.
(1) Write a program to add two 6 x 6 matrices.
(2) Write a program to multiply any two 3 x 3 matrices.
(3) Write a program to sort all the elements of a 4 x 4
matrix.
(4) Write a program to obtain the determinant value of a
5 x 5 matrix.
Solution:
--------------------------------------------------------------------------------------------------------------
(j) Write a program that interchanges the odd and even
components of an array.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,a[6],even,temp;
clrscr();
printf("enter the numbers: nn");
for(i=0;i<6;i++) {
scanf("%d",&a[i]);
}
clrscr();
printf("narray without exchanging even and odd numbers:nn");
for(i=0;i<6;i++) {
printf("%2d ",a[i]);
}
printf("nnarray after exchanging even and odd numbers: nn");
for(i=0;i<6;i++) {
for(j=i+1;j<6;j++) {
/* if one element is even and another after that is odd 
,they will be exchanged */
if((a[i]%2)!=0 && (a[j]%2)==0) {
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
for(i=0;i<6;i++) {
printf("%2d ",a[i]);
}
getch();
}
--------------------------------------------------------------------------------------------------------------
(k) Write a program to find if a square matrix is
symmetric.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,r,c,sym;
int a[100][100],b[100][100];
clrscr();
printf(" enter number of rows of matrix: ");
scanf("%d",&r);
printf("nnenter number of columns of matrix: ");
scanf("%d",&c);
clrscr();
printf("enter the elements in matrix: n");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
scanf("%d",&a[i][j]);
}
}
clrscr();
printf("nmatrix you entered isnn");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("%d ",a[i][j]);
}
printf("n");
}
printf("nntranspose of matrix is nn");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
b[j][i]=a[i][j];
}
}
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("%d ",b[i][j]);
}
printf("n");
}
/* finding if square matrix is equal to it's transpose to be symmetric */
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
if(a[i][j]!=b[i][j])
sym=1;
}
}
if(sym==1)
printf("nSquare matrix is not symmetric.n");
else
printf("nSquare matrix is symmetric.n");
getch();
}
----------------------------------------------------------------------------------------------------------------
(l) Write a function to find the norm of a matrix. The
norm is defined as the square root of the sum of squares
of all elements in the matrix.
Solution:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
int i,j,r,c,a[100][100];
int norm=0,sum=0;
clrscr();
printf("nEnter the number of rows: ");
scanf("%d",&r);
printf("nnEnter the number of coloumns: ");
scanf("%d",&c);
clrscr();
printf("Enter elements of %d x %d array: nn",r,c);
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
scanf("%d",&a[i][j]);
}
}
clrscr();
printf("nmatrix you entered is: nn");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("%2d ",a[i][j]);
}
printf("n");
}
/* norm of the matrix */
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
sum=sum+(a[i][j]*a[i][j]);
}
}
norm=sqrt(sum);
printf("nNorm of matrix = %d",norm);
getch();
}
----------------------------------------------------------------------------------------------------------------
(m) Given an array p[5], write a function to shift it
circularly left by two positions. Thus, if p[0] = 15, p[1]=
30, p[2] = 28, p[3]= 19 and p[4] = 61 then after the shift
p[0] = 28, p[1] = 19, p[2] = 61, p[3] = 15 and p[4] = 30.
Call this function for a (4 x 5 ) matrix and get its rows
left shifted.
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,p[]={15,30,28,19,61};
int a[4][5];
clrscr();
printf("Array before shift:nn");
for(i=0;i<5;i++) {
printf("%2d ",p[i]);
}
func(p);
printf("nnArray after shift:nn");
for(i=0;i<5;i++) {
printf("%2d ",p[i]);
}
printf("nnnenter the elements of 4x5 matrix: nn");
for(i=0;i<4;i++) {
for(j=0;j<5;j++) {
scanf("%d",&a[i][j]);
}
}
clrscr();
printf("matrix you enterd before shift: nn");
for(i=0;i<4;i++) {
for(j=0;j<5;j++) {
printf("%2d ",a[i][j]);
}
printf("n");
}
printf("nnafter shift:nn");
/* shift the rows of matrix */
for(i=0;i<4;i++) {
func(a[i]);
}
for(i=0;i<4;i++) {
for(j=0;j<5;j++) {
printf("%2d ",a[i][j]);
}
printf("n");
}
getch();
}
func(int q[5]) {
int a,t1,t2,t3;
t1=q[0];
t2=q[1];
q[0]=q[2];
q[1]=q[3];
q[2]=q[4];
q[3]=t1;
q[4]=t2;
return q[5];
}
----------------------------------------------------------------------------------------------------------
(n) A 6 x 6 matrix is entered through the keyboard and
stored in a 2-dimensional array mat[7][7]. Write a
program to obtain the Determinant values of this matrix.
Solution:
----------------------------------------------------------------------
--------
(o) For the following set of sample data, compute the
standard deviation and the mean.
-6, -12, 8, 13, 11, 6, 7, 2, -6, -9, -10, 11, 10, 9, 2
Solution:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
int a[15]={-6,-12,8,13,11,6,7,2,-6,-9,-10,11,10,9,2};
int i,j;
float temp,sd,sum=0,mean,x;
clrscr();
printf("ndata set: nn");
for(i=0;i<15;i++) {
printf(" %3d ",a[i]);
}
printf("n");
for(i=0;i<15;i++) {
sum=sum+a[i]; /* adding all the numbers */
}
mean=sum/15; /* calculating the mean */
/* computing standard deviation */
for(i=0;i<15;i++) {
a[i]=pow((a[i]-mean),2);
x=x+a[i];
}
temp=x/15;
sd=sqrt(temp);
printf("nnttmean= %fnttstandard deviation = %fn",mean,sd);
getch();
}
--------------------------------------------------------------------------------------------------------------
(p) The area of a triangle can be computed by the sine
law when 2 sides of the triangle and the angle between
them are known.
Area = (1 / 2 ) ab sin ( angle )
Given the following 6 triangular pieces of land, write a
program to find their area and determine which is
largest,
Plot No.
a
b
angle
137.4
80.9
0.78
155.2
92.62
0.89
149.3
97.93
1.35
160.0
100.25
9.00
155.6
68.95
1.25
149.7
120.0
1.75
Solution:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
float a[6][3]={ {137.4, 80.9, 0.78},
{155.2, 92.62, 0.89},
{149.3, 97.93, 1.35},
{160.0, 100.25, 9.00},
{155.6, 68.95, 1.25},
{149.7, 120.0, 1.75} };
float big=0,area;
int sr=0,i;
clrscr();
for(i=0;i<6;i++) {
area=(1.0/2.0)*a[i][0]*a[i][1]*sin(a[i][2]);
if(area>big) {
big=area;
sr=i;
}
}
printf("nnPlot no. %d is the biggest.n",sr);
printf("nArea of plot no. %d = %fn",sr,big);
getch();
}
-
------------------------------------------------------------------------------------------------------------
(q) For the following set of n data points (x, y), compute
the correlation coefficient r,
x
y
34.22
102.43
39.87
100.93
41.85
97.43
43.23
97.81
40.06
98.32
53.29
98.32
53.29
100.07
54.14
97.08
49.12
91.59
40.71
94.85
55.15
94.65
Solution:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
float a[][2]={ {34.22,102.43},
{39.87,100.93},
{41.85,97.43},
{43.23,97.81},
{40.06,98.32},
{53.29,98.32},
{53.29,100.07},
{54.14,97.08},
{49.12,91.59},
{40.71,94.85},
{55.15,94.65} };
int i,n=0;
float x2,y2,x,y,x_y,n_x2,n_y2,r;
clrscr();
for(i=0;i<11;i++) {
x2= x2 + ( a[i][0] * a[i][0] ); /* computing square of x */
y2= y2 + ( a[i][1] * a[i][1] ); /* computing square of y */
x= x + a[i][0]; /* computing total of x */
y= y + a[i][1]; /* computing total of y */
x_y= x_y + ( a[i][0] * a[i][1] ); /* computing total of x * y */
n++;
}
n_x2= n * x2;
n_y2= n * y2;
r= ( x_y - x*y )/sqrt((n_x2-x2) * (n_y2-y2));
printf(" sum of square of x = %fnn",x2);
printf(" sum of square of y = %fnn",y2);
printf(" sum of x = %fnn",x);
printf(" sum of y = %fnn",y);
printf(" sum of x * y = %fnn",x_y);
printf(" sum of n*x2 = %fnn",n_x2);
printf(" sum of n*y2 = %fnn",n_y2);
printf("nnnCorrelation cofficient = %fn",r);
getch();
}
-------------------------------------------------------------------------------------------------------------
(r) For the following set of point given by
(x, y) fit a straight line given by
y = a + bx
x
y
3.0
1.5
4.5
2.0
5.5
3.5
6.5
5.0
7.5
6.0
8.5
7.5
8.0
9.0
9.0
10.5
9.5
12.0
10.0
14.0
Solution:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
float data[][2]= { {3.0,1.5},
{4.5,2.0},
{5.5,3.5},
{6.5,5.0},
{7.5,6.0},
{8.5,7.5},
{8.0,9.0},
{9.0,10.5},
{9.5,12.0},
{10.0,14.0} };
int i,n=0;
float sx,sy,x2,y2,xy,a,b,Y;
clrscr();
for(i=0;i<10;i++) {
sx = sx + data[i][0];
sy = sy + data[i][1];
x2= x2 + ( data[i][0] * data[i][0] );
y2= y2 + ( data[i][1] * data[i][1] );
xy = xy + ( data[i][0] * data[i][1] );
n++;
}
printf(" sum of x = %fn",sx);
printf(" sum of y = %fn",sy);
printf(" sum of x2 = %fn",x2);
printf(" sum of y2 = %fn",y2);
printf(" sum of x*y = %fn",xy);
printf(" total number = %dn",n);
b = ( (n*xy) - (sx*sy) ) / ( n*x2 - (sx*sx) );
a = (sy/n) - b*(sx/n);
Y= a + b*sx ;
printf("nnvalue of a = %fnn",a);
printf("value of b = %fnn",b);
printf(" Y = %f nn",Y);
getch();
}
-------------------------------------------------------------------------------------------------------------
(s) The X and Y coordinates of 10 different
points are entered through the keyboard.
Write a program to find the distance of
last point from the first point (sum of
distance between consecutive points).
Solution:
#include<stdio.h>
#include<conio.h>
void main() {
float a[10][2],sx,sy;
int i;
clrscr();
for(i=0;i<10;i++) {
printf("Enter coordinates of point number %d:nn",i+1);
printf("Value of X coordinate: ");
scanf("%f",&a[i][0]);
printf("nValue of Y coordinate: ");
scanf("%f",&a[i][1]);
clrscr();
}
for(i=0;i<10;i++) {
if(i>0 && i<10-1) {
sx = sx + a[i][0];
sy = sy = a[i][1];
}
}
printf(" First coordinate: X = %ftY = %fnn",a[0][0],a[0][1]);
printf(" Last coordinate: X = %ftY = %fnn",a[9][0],a[9][1]);
printf("nDistance between them: X = %ftY = %fn",sx,sy);
getch();
}

More Related Content

What's hot

Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C BUBT
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in CBUBT
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CBUBT
 
The solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinThe solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinShariful Haque Robin
 
Let us c (by yashvant kanetkar) chapter 1 solution
Let us c (by yashvant kanetkar) chapter 1 solutionLet us c (by yashvant kanetkar) chapter 1 solution
Let us c (by yashvant kanetkar) chapter 1 solutionHazrat Bilal
 
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1rohit kumar
 
C programs
C programsC programs
C programsMinu S
 
Printing different pyramid patterns of numbers,alphabets and stars using C.
Printing different pyramid patterns of numbers,alphabets and stars using C.Printing different pyramid patterns of numbers,alphabets and stars using C.
Printing different pyramid patterns of numbers,alphabets and stars using C.Hazrat Bilal
 
LET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERSLET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERSKavyaSharma65
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)Make Mannan
 
Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in cBUBT
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robinAbdullah Al Naser
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab FileKandarp Tiwari
 

What's hot (20)

Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C
 
Ansi c
Ansi cAnsi c
Ansi c
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in C
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in C
 
The solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinThe solution manual of programming in ansi by Robin
The solution manual of programming in ansi by Robin
 
Let us c (by yashvant kanetkar) chapter 1 solution
Let us c (by yashvant kanetkar) chapter 1 solutionLet us c (by yashvant kanetkar) chapter 1 solution
Let us c (by yashvant kanetkar) chapter 1 solution
 
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
 
C programs
C programsC programs
C programs
 
Printing different pyramid patterns of numbers,alphabets and stars using C.
Printing different pyramid patterns of numbers,alphabets and stars using C.Printing different pyramid patterns of numbers,alphabets and stars using C.
Printing different pyramid patterns of numbers,alphabets and stars using C.
 
C function
C functionC function
C function
 
Function in c
Function in cFunction in c
Function in c
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
LET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERSLET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERS
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in c
 
Function in c program
Function in c programFunction in c program
Function in c program
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robin
 
Function in C
Function in CFunction in C
Function in C
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
Function C programming
Function C programmingFunction C programming
Function C programming
 

Similar to Chapter 8 c solution

Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020vrgokila
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkarsandeep kumbhkar
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using CBilal Mirza
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given numberMainak Sasmal
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given numberMainak Sasmal
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Er Ritu Aggarwal
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C ProgramsKandarp Tiwari
 
Data Structure in C Programming Language
Data Structure in C Programming LanguageData Structure in C Programming Language
Data Structure in C Programming LanguageArkadeep Dey
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointersvinay arora
 
C basics
C basicsC basics
C basicsMSc CST
 
C programs Set 2
C programs Set 2C programs Set 2
C programs Set 2Koshy Geoji
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfAshutoshprasad27
 

Similar to Chapter 8 c solution (20)

Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkar
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
C Programming Example
C Programming ExampleC Programming Example
C Programming Example
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
SaraPIC
SaraPICSaraPIC
SaraPIC
 
Arrays
ArraysArrays
Arrays
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
Array Programs.pdf
Array Programs.pdfArray Programs.pdf
Array Programs.pdf
 
C Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossainC Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossain
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
Data Structure in C Programming Language
Data Structure in C Programming LanguageData Structure in C Programming Language
Data Structure in C Programming Language
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
 
C basics
C basicsC basics
C basics
 
C programs Set 2
C programs Set 2C programs Set 2
C programs Set 2
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
 

Recently uploaded

Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxkalpana413121
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptAfnanAhmad53
 

Recently uploaded (20)

Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .ppt
 

Chapter 8 c solution

  • 1. Write a program to copy the contents of one array into another in the reverse order. Source Code : #include<stdio.h> void main() { int a[10],b[10],i,j; clrscr(); printf("nEnter Elements : "); for(i=0;i<10;i++) { scanf("%d",&a[i]); } for(i=0,j=9;i<10;i++,j--) { b[i]=a[j]; } printf("nArray after Copying in Reverse Order : "); for(i=0;i<10;i++) { printf("%d ",b[i]); } getch(); } Output : Enter Elements : 2 6 3 5 9 8 7 4 1 0 Array after Copying in Reverse Order : 0 1 4 7 8 9 5 3 6 2 #include<stdio.h> #include<conio.h> void main() { int i,n=10,a[20],b[20]; clrscr(); printf("How many element do you wish to enter in array? :"); scanf("%d",&n); printf("nEnter the Elements:n"); for(i=0;i<n;i++) { printf("Enter Element No %d : ",1+i); scanf("%d",&a[i]);
  • 2. } printf("n Original ARRAY: n"); for(i=0;i<n;i++) printf(" %d ",a[i]); for(i=0;i<n;i++) { b[n-1-i]=a[i]; } printf("n Copied ARRAY: n"); for(i=0;i<n;i++) printf(" %d ",b[i]); getch(); } //*********************** //www.botskool.com //*********************** Program to print array element in reverse order. Code for Program to print array element in reverse order in C Programming #include<conio.h> #include<stdio.h> #include<stdlib.h> int main() { int *ptr,i,n; clrscr(); printf("Enter the no of elements:"); scanf("%d",&n); ptr=(int *)malloc(sizeof(int)*n); if(ptr==NULL) { printf("Not enough memory"); exit(1); } for(i=0; i<n; i++) { printf("Enter %d element : ",i+1); scanf("%d",&ptr[i]); } printf("Array in original ordern");
  • 3. for(i=0; i<n; i++) { printf("%dn",ptr[i]); } printf("Array in reverse ordern"); for(i=n-1; i>=0; i--) { printf("%dn",ptr[i]); } getch(); return 0; } void reverse( int array[], int length) { int ii, temp; int jj = 0; int *tempArray = (int)malloc( length * sizeof( int)); for ( ii = length-1; ii >= 0; ii--) { tempArray[jj] = array[ii]; jj += 1; } array = *tempArray; for (ii = 0; ii <= length-1; ii++) { printf("DEBUGn"); temp = tempArray[ii]; array[ii] = temp; } free( tempArray); } #include<stdio.h> #include<conio.h> voidmain() { int i,j,a[100],b[100]; printf("How many numbers youwant to store:=n"); scanf("%d",&j); printf("Enter the numbers:=n"); for(i=0;i<j;i++) { scanf("%d",&a[i]); } for(i=0;i<j;i++) { b[i]=a[j-i-1];
  • 4. } printf("Reversedorder:=n"); for(i=0;i<j;i++) { printf("%dn",b[i]); } getch(); } Write a program to copy the contents of one array into another in the reverse order. void main() { int arr1[5]={1,2,3,4,5}; int arr2[5]; int i,k; for (i=4,k=0;i>=0;i--,k++) arr2[k]=arr1[i]; for(i=0;i<5;i++) printf("nValue of arr2[%d] is %d",i,arr2[i]); } With Pointers void main() { int arr1[5]={1,2,3,4,5}; int arr2[5]; int *m; int i,*j,k,l=5; j=arr1; m=arr2; func(j,m,l); for(i=0;i<5;i++) printf("nValue of arr2[%d] is %d",i,arr2[i]); } func(int *j, int *m, int l) { int i; for(j=j+4,i=0;i<5;i++,j--,m++) *m=*j; } #include<stdio.h>
  • 5. #include<conio.h> main() { int num[10]; int x; for(x=0;x<10;x++) { printf("Enter number %d : ",x); scanf("%d", &num[x]); } for(x=0;x<10;x++) { printf(" %d ",num[x]); } //clrscr (); num[x]=0; for(x=10;x>-1;x--) { printf(" %d ",num[x]); } getch(); } C program to reverse an array: This program reverses the array elements. For example if a is an array of integers with three elements such that a[0] = 1 a[1] = 2 a[2] = 3 Then on reversing the array will be a[0] = 3 a[1] = 2 a[0] = 1 Given below is the c code to reverse an array. C programming code #include <stdio.h> int main() { int n, c, d, a[100], b[100];
  • 6. printf("Enter the number of elements in arrayn"); scanf("%d", &n); printf("Enter the array elementsn"); for (c = 0; c < n ; c++) scanf("%d", &a[c]); /* * Copying elements into array b starting from end of array a */ for (c = n - 1, d = 0; c >= 0; c--, d++) b[d] = a[c]; /* * Copying reversed array into original. * Here we are modifying original array, this is optional. */ for (c = 0; c < n; c++) a[c] = b[c]; printf("Reverse array isn"); for (c = 0; c < n; c++) printf("%dn", a[c]); return 0; } Download Reverse array program. Output of program:
  • 7. Reverse array by swapping (without using additionalmemory) #include <stdio.h> int main() { int array[100], n, c, t, end; scanf("%d", &n); end = n - 1; for (c = 0; c < n; c++) { scanf("%d", &array[c]); } for (c = 0; c < n/2; c++) { t = array[c]; array[c] = array[end]; array[end] = t; end--; } printf("Reversed array elements are:n"); for (c = 0; c < n; c++) { printf("%dn", array[c]); } return 0; } C program to reverse an array using pointers #include <stdio.h> #include <stdlib.h> void reverse_array(int*, int); int main() { int n, c, *pointer; scanf("%d",&n); pointer = (int*)malloc(sizeof(int)*n); if( pointer == NULL ) exit(EXIT_FAILURE); for ( c = 0 ; c < n ; c++ ) scanf("%d",(pointer+c)); reverse_array(pointer, n); printf("Original array on reversal isn"); for ( c = 0 ; c < n ; c++ )
  • 8. printf("%dn",*(pointer+c)); free(pointer); return 0; } void reverse_array(int *pointer, int n) { int *s, c, d; s = (int*)malloc(sizeof(int)*n); if( s == NULL ) exit(EXIT_FAILURE); for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ ) *(s+d) = *(pointer+c); for ( c = 0 ; c < n ; c++ ) *(pointer+c) = *(s+c); free(s); }
  • 9. Chap 8[D]a Search quantity of instances in Array Twenty-five numbers are entered from the keyboard into an array. The number to be searched is entered through the keyboard by the user. Write a program to find if the number to be searched is present in the array and if it is present, display the number of times it appears in the array. void main() { int arr[25]; int a,d,i; for(i=0;i<25;i++) { printf("nKey %d) value",i); scanf("%d",&arr[i]); } printf("n25 numbers stored, enter any integer again"); scanf("%d",&d); for(i=0,a=0;i<25;i++) { if(arr[i]==d) a++; } if(a>0) printf("nThe integer appeared %d times in the array",a); else printf("nThe integer did not appear in the array"); } hap8[D]b Finding +tive -tive zeros, odd and even numbers in array Twenty-five numbers are entered from the keyboard into an array. Write a program to find out how many of them are positive, how many are negative, how many are even and how many odd. void main() { int arr[25]; int a,b,c,d,e,i; a=0; b=0;
  • 10. c=0; d=0; e=0; for(i=0;i<25;i++) { printf("nKey the %d) value",i); scanf("%d",&arr[i]); } for(i=0;i<25;i++) { if(arr[i]>0) a++; if(arr[i]<0) b++; if(arr[i]==0) c++; if(arr[i]%2==0) d++; else e++; } if(a>0) printf("nThere are %d positive integers",a); if(b>0) printf("nThere are %d negative integers",b); if(c>0) printf("nThere are %d zeros",c); if(d>0) printf("nThere are %d even numbers",d); if(e>0) printf("nThere are %d odd numbers",e); } Chap8[D]c Selection sort
  • 11. Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms) − Selection sort − Bubble Sort − Insertion Sort /* Selection sort */ void main() { int arr[25]; int a,b,d,i; printf("nInput 25 numbers into array");
  • 12. for(i=0;i<25;i++) { printf("nKey the %d) value",i); scanf("%d",&arr[i]); } printf("nStarting selection sorting"); for(i=0;i<24;i++) { for(d=i+1;d<25;d++) { a=arr[i]; b=arr[d]; arr[i]=b; arr[d]=a; } } printf("nSelection sorting done"); for(i=0;i<25;i++) printf("n%d) value is %d",i,arr[i]); } Chap8[D]c Buuuubbbble sort Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms)− Selection sort − Bubble Sort − Insertion Sort
  • 13. /*Bubble sort*/ void main() { int arr[25]; int a,b,c,d,i; printf("nInput 25 numbers into the array"); for(i=0;i<25;i++) { printf("nKey the %d) value",i); scanf("%d",&arr[i]); }
  • 14. printf("nStarting bubble sort"); for(i=24;i>0;i--) { for(b=0,c=b+1;c <=i;b++,c ++) { a=arr[b]; d=arr[c]; arr[b]=d; arr[c]=a; } } printf("nBubble sort done"); for(i=0;i<25;i++) printf("n%d value is %d",i,arr[i]); } Chap8[D]c Insertion sort Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms) − Selection sort − Bubble Sort − Insertion Sort /*Insertion sort*/ void main()
  • 15. { int arr[25]; int a,b,c,i; printf("nInput 25 numbers into the array"); for(i=0;i<25;i++) { printf("nKey in the %d) value",i); scanf("%d",&arr[i]); } printf("nStarting insertion sort"); for(a=1;a<25;a++) { b=arr[0]; c=arr[a]; arr[0]=c; arr[a]=b; } printf("nInsertion sort done"); for(i=0;i<25;i++) printf("nThe %d) value is%d",i,arr[i]); } Chap8[D]d Sieve of Eratosthenes Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes. step 1 Fill an array num[100] with numbers from 1 to 100 step 2 Starting with the second entry in the array, set all its multiples to zero. step 3 Proceed to the next non-zero element and set all its multiples to zero. step 4 Repeat step 3 till you have set up the multiples of all the non-zero elements to zero step 5 At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.
  • 16. Chap8[I]a Reversing contents and copy to another array Write a program to copy the contents of one array into another in the reverse order. void main() { int arr1[5]={1,2,3,4,5}; int arr2[5]; int i,k; for (i=4,k=0;i>=0;i--,k++) arr2[k]=arr1[i]; for(i=0;i<5;i++) printf("nValue of arr2[%d] is %d",i,arr2[i]); } With Pointers void main() { int arr1[5]={1,2,3,4,5}; int arr2[5]; int *m; int i,*j,k,l=5; j=arr1; m=arr2; func(j,m,l);
  • 17. for(i=0;i<5;i++) printf("nValue of arr2[%d] is %d",i,arr2[i]); } func(int *j, int *m, int l) { int i; for(j=j+4,i=0;i<5;i++,j--,m++) *m=*j; } Chap8[I]b Check similar integers in array If an array arr contains n elements, then write a program to check if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on. This program will have repeated results if the input contains more than 2 same integers void main() { int arr[25]; int i,*j,k; j=arr; printf("nInput 25 integers"); for(i=0;i<25;i++,j++) { printf("nKey in the %d) value",i+1); scanf("%d",&*j); } for(i=0;i<25;i++) { for(k=24;k>i;k--) if(arr[i]==arr[k]) printf("nArray [%d] = Array[%d]",i,k); } } Chap8[I]c Finding smallest number in array using pointers
  • 18. Find the smallest number in an array using pointers. Chap8[L]a Initialising 3D array How will you initialize a three-dimensional array threed[3][2][3]? How will you refer the first and last element in this array? void main() { int threed[3][2][3]={ { 1,2,3, 4,5,6 }, { 7,8,9, 10,11,12 }, { 13,14,15, 16,17,18 } }; printf("nFirst element of array is %dnLast element of the array is %d",threed[0][0][0],threed[2][1][2]); }
  • 19. hap8[L]b Pick largest number from matrix Write a program to pick up the largest number from any 5 row by 5 column matrix. Write a program to obtain transpose of a 4 x 4 matrix. The transpose of a matrix is obtained by exchanging the elements of each row with the elements of the corresponding column. void main() { int arr[4][4]; int i,j,a,b,f; printf("nInput numbers to 4*4 matrix"); for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("nKey in the [%d][%d]) value",i+1,j+1); scanf("%d",&arr[i][j]); } } for(i=0;i<4;i++) { for(j=0,f=0;j<4;j++) { if(i!=j&&f==0) continue; a=arr[i][j]; b=arr[j][i];
  • 20. arr[i][j]=b; arr[j][i]=a; f=1; } } for(i=0;i<4;i++) { for(j=0;j<4;j++) printf("%d ",arr[i][j]); printf("n"); } } Creating your own strcat() Creating your own strcat() void main() { char source[]="Folks!"; char target[30]="Hello"; scat(target,source); printf("nSource string = %s",source); printf("nTarget string = %s",target); } scat(char *m,char *n) { char *p; p=m; while(*n!='0') { if(*m=='0'||m>p+6) { *m=*n; n++; } m++; }
  • 21. *m='0'; } Very often in fairs we come across a puzzle that contains 15 numbered square pieces mounted on a frame. These pieces can be moved horizontally or vertically. A possible arrangement of these pieces is shown below: As you can see there is a blank at bottom right corner. Implement the following procedure through a program: Draw the boxes as shown above. Display the numbers in the above order. Allow the user to hit any of the arrow keys (up, down, left, or right). If user hits say, right arrow key then the piece with a number 5 should move to the right and blank should replace the original position of 5. Similarly, if down arrow key is hit, then 13 should move down and blank should replace the original position of 13. If left arrow key or up arrow key is hit then no action should be taken. The user would continue hitting the arrow keys till the numbers aren’t arranged in ascending order. Keep track of the number of moves in which the user manages to arrange the numbers in ascending order. The user who manages it in minimum number of moves is the one who wins. How do we tackle the arrow keys? We cannot receive them using scanf( ) function. Arrow keys are special keys which are identified by their ‘scan codes’. Use the following function in your program. It would return the scan code of the arrow key being hit. Don’t worry about how this function is written. We are going to deal with it later. The scan codes for the arrow keys are: up arrow key – 72 down arrow key – 80 left arrow key – 75 right arrow key – 77 /* Returns scan code of the key that has been hit */ #include "dos.h" getkey( ) { union REGS i, o ; while ( !kbhit( ) ) ; i.h.ah = 0 ; int86 ( 22, &i, &o ) ; return ( o.h.ah ) ; }
  • 22. ANS: #include "dos.h" void main() { void creategrid(); int g,c; int arr[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0}; clrscr(); creategrid(); printarray(arr); for(g=15,c=0;;) { int k,a,b,i; k=getkey(); if(k==80) { if((g-4)<0) a="arr[g-4];" b="arr[g];" k="="72)">15) continue; a=arr[g+4]; b=arr[g]; arr[g+4]=b; arr[g]=a; go(g); printf("%d",arr[g]); go(g+4); printf("%c%c",0,0); go(g+4); c++; g+=4; } if(k==75) { if(g==3g==7g==11g==15) continue; a=arr[g+1]; b=arr[g]; arr[g+1]=b; arr[g]=a; go(g); printf("%d",arr[g]); go(g+1);
  • 24. break; case 1: gotoxy(12,5); break; case 2: gotoxy(16,5); break; case 3: gotoxy(20,5); break; case 4: gotoxy(8,9); break; case 5: gotoxy(12,9); break; case 6: gotoxy(16,9); break; case 7: gotoxy(20,9); break; case 8: gotoxy(8,13); break; case 9: gotoxy(12,13); break; case 10: gotoxy(16,13); break; case 11: gotoxy(20,13); break; case 12: gotoxy(8,17); break; case 13: gotoxy(12,17); break; case 14: gotoxy(16,17); break; case 15: gotoxy(20,17); break; } }
  • 25. getkey() { union REGS i,o; while(!kbhit()) ; i.h.ah=0; int86(22,&i,&o); return(o.h.ah); } printarray(int *m) { int a,b,i,j; for(a=5,i=0;a<=17;a+=4,i++) { for(b=8,j=0;b<=20;b+=4,j++) { gotoxy(b,a); printf("%d",*(m+(i*4)+j)); } } gotoxy(20,17); printf("%c",0); } void creategrid() { int a,b; for(a=3;a<=19;a+=4) { for(b=6;b<=22;b++) { if(b==6(b-6)%4==0) { if(a==3) { if(b==6) { gotoxy(6,3); printf("%c",218); } else if(b==22) {
  • 27. printf("%c",197); } } } else { printf("%c",196); } } } for(b=6;b<=22;b+=4) { for(a=4;a<=18;a++) { if((a-3)%4==0) continue; else { gotoxy(b,a); printf("%c",179); } } } } Write a function to find the norm of a matrix. The norm is defined as the square root of the sum of squares of all elements in the matrix. he area of a triangle can be computed by the sine law when 2 sides of the triangle and the angle between them are known.
  • 28. Area = (1 / 2 ) ab sin ( angle ) Given the following 6 triangular pieces of land, write a program to find their area and determine which is largest, #include math.h (include arrows) void main() { float arr[6][3]; int i,j,d; float area,c=0; for(i=0;i<6;i++) { for(j=0;j<3;j++) { printf("nKey in the [%d][%d] value",i+1,j+1); scanf("%f",&arr[i][j]); } } for(i=0;i<6;i++) { area=(1.0/2.0)*arr[i][0]*arr[i][1]*sin(arr[i][2]); if(area>c) { printf("n1"); c=area; d=i; }
  • 29. } printf("nThe biggest plot of land is plot no. %d with area %f",d+1,c); } For the following set of n data points (x, y), compute the correlation coefficient r, given by #include math.h (include arrows) void main() { float arr[11][2]={ 34.22,102.43, 39.87,100.93,
  • 30. 41.85,97.43, 43.23,97.81, 40.06,98.32, 53.29,98.32, 53.29,100.07, 54.14,97.08, 49.12,91.59, 40.71,94.85, 55.15,94.65 }; int i,j; float sx=0,sy=0,sx2=0,sy2=0,sxy=0,b,r; /*calculating summation x*/ for(i=0;i<11;i++) sx=sx+arr[i][0]; printf("nsummation x is %f",sx); /*calculating summation y*/ for(i=0;i<11;i++) sy=sy+arr[i][1]; printf("nsummation y is %f",sy); /*calculating summation x2*/ for(i=0;i<11;i++) sx2=sx2+(arr[i][0]*arr[i][0]); printf("nsummation x2 is %f",sx2); /*calculating summation y2*/ for(i=0;i<11;i++) sy2=sy2+(arr[i][1]*arr[i][1]); printf("nsummation sy2 is %f",sy2); /*calculating summation xy*/ for(i=0;i<11;i++) sxy=sxy+(arr[i][0]*arr[i][1]); printf("nsummation sxy is %f",sxy); /*calculating bottom part*/ b=(i*sx2-(sx*sx))*(i*sy2-(sy*sy)); printf("nbottom is %f",b); /*calculating coefficient r*/ r=(sxy-(sx*sy))/(sqrt(b));
  • 31. printf("n The correlation coefficient is %f",r); } For the following set of point given by (x, y) fit a straight line given by y = a + bx where, #include math.h (include arrows) void main() { float arr[10][2]={ 3.0,1.5, 4.5,2.0,
  • 32. 5.5,3.5, 6.5,5.0, 7.5,6.0, 8.5,7.5, 8.0,9.0, 9.0,10.5, 9.5,12.0, 10.0,14.0 }; int i,j; float sx=0,sy=0,sx2=0,sxy=0,my,mx,a,b; /* for(i=0;i<10;i++) { for(j=0;j<2;j++) { printf("nKey in the [%d][%d] value",i+1,j+1); scanf("%f",&arr[i][j]); } } */ /*calculating summation x*/ for(i=0;i<10;i++) sx=sx+arr[i][0]; /*calculating summation y*/ for(i=0;i<10;i++) sy=sy+arr[i][1]; /*calculating summation x2*/ for(i=0;i<10;i++) sx2=sx2+(arr[i][0]*arr[i][0]); /*calculating summation xy*/ for(i=0;i<10;i++) sxy=sxy+(arr[i][0]*arr[i][1]); my=sy/i; mx=sx/i; b=((i*sxy)-(sx*sy))/((i*sx2)-(sx*sx)); a=my-(b*mx);
  • 33. printf("nThe value of a is %fnThe value of b is %f",a,b); } Creating your own strcat() void main() { char source[]="Folks!"; char target[30]="Hello"; scat(target,source); printf("nSource string = %s",source); printf("nTarget string = %s",target); } scat(char *m,char *n) { char *p; p=m; while(*n!='0') { if(*m=='0'||m>p+6) { *m=*n; n++; } m++; } *m='0'; }
  • 34. et Us C / Chapter 8(Arrays) Exercise [D] (a) Twenty-five numbers are entered from the keyboard into an array. The number to be searched is entered through the keyboard by the user. Write a program to find if the number to be searched is present in the array and if it is present, display the number of times it appears in the array. Solution: #include<stdio.h> #include<conio.h> void main() { int i,arr[25],prsnt=0,num; clrscr(); printf("Please enter 25 numbers: n"); for(i=0;i<25;i++) { scanf("%d",&arr[i]); } printf("nnPlease enter the number to be searched: "); scanf("%d",&num);
  • 35. for(i=0;i<25;i++) { if(num==arr[i]) prsnt=prsnt+1; } if(prsnt==0) { printf("nnNumber does not present in the array.n"); } else { printf("nnNumber presents in the array.n"); printf("nNumber of times it appears = %d.n",prsnt); } getch(); } --------------------------------------------------------------------------------------------------------------- b) Twenty-five numbers are entered from the keyboard into an array. Write a program to find out how many of them are positive, how many are negative, how many are even and how many odd. Solution:
  • 36. #include<stdio.h> #include<conio.h> void main() { int i,arr[25],tz=0,tp=0,tn=0; clrscr(); printf("Enter numbers in the array: n"); for(i=0;i<25;i++) { scanf("%d",&arr[i]); if(arr[i]<0){ tn=tn+1; } if(arr[i]==0){ tz=tz+1; } if(arr[i]>0){ tp=tp+1; } } printf("nnnTotal zeros = %dn",tz); printf("Total positive numbers = %dn",tp); printf("Total negative numbers = %dn",tn);
  • 37. getch(); } ---------------------------------------------------------------------------------------------------------------- (c) Implement the Selection Sort, Bubble Sort and Insertion sort algorithms on a set of 25 numbers. (Refer Figure 8.11 for the logic of the algorithms) − Selection sort − Bubble Sort − Insertion Sort Solution: ---------------------------------------------------------------------------------------------------------------- (d) Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes. step 1 Fill an array num[100] with numbers from 1 to 100 step 2
  • 38. Starting with the second entry in the array, set all its multiples to zero. step 3 Proceed to the next non-zero element and set all its multiples to zero. step 4 Repeat step 3 till you have set up the multiples of all the non-zero elements to zero step 5 At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers. Solution: #include<stdio.h> #include<conio.h> void main() { int i,j,a[100]; clrscr(); for(i=0;i<100;i++) { a[i]=i+1; }
  • 39. printf("n100 numbers in the array:nn"); for(i=0;i<100;i++) { printf("%3d ",a[i]); } printf("nnafter implementing eratothene's sieve:nn"); for(i=2;i<100;i++) { for(j=2;j<a[i];j++) { if(a[i]%j==0) a[i]=0; } } i=a[0]; for(;i<100;i++) { printf("%3d ",a[i]); } printf("nnprime numbers are: nn"); for(i=a[0];i<100;i++) {
  • 40. if(a[i]!=0) printf("%3d ",a[i]); } getch(); } --------------------------------------------------------------------------------------------------------------- Exercise [I] (a) Write a program to copy the contents of one array into another in the reverse order. Solution: #include<stdio.h> #include<conio.h> void main() { int i,j,k,a1[5],a2[5]; clrscr(); for(i=1;i<=5;i++) { scanf("%d",&a1[i]); }
  • 41. printf("nnThe elements you enterd are:n"); for(i=1;i<=5;i++) { printf(" %d",a1[i]); } printf("nnElements in reversed order:n"); for(i=5,j=1;i>=1,j<=5;i--,j++) { k=a1[i]; a2[j]=k; printf(" %d",a2[j]); } getch(); } --------------------------------------------------------------------------------------------------------------- (b) If an array arr contains n elements, then write a program to check if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on. Solution: #include<stdio.h> #include<conio.h>
  • 42. void main() { int arr[100]; int n,i,f=0; clrscr(); printf("enter total elements of array(n): "); scanf("%d",&n); printf("nnenter "n" elements of array: nn"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } clrscr(); for(i=0;i<n;i++) { if(arr[i]==arr[n-(i+1)]) { /* if element is equal, according to the problem, it will be printed */ f=f+1; printf("element no: %d = %d ",i,arr[i]); } } if(f==0) printf("nnNo such element found.n");
  • 43. getch(); } --------------------------------------------------------------------------------------------------------------- (c) Find the smallest number in an array using pointers. Solution: #include<stdio.h> #include<conio.h> void main() { int i,n,*p,*s,a[100]; clrscr(); printf("enter how many numbers you want to save in array: "); scanf("%d",&n); printf("nnenter %d number in array:n",n); for(i=0;i<n;i++) { scanf("%d",&a[i]); }
  • 44. clrscr(); printf("array you entered: nn"); for(i=0;i<n;i++) { printf("%2d ",a[i]); } printf("nn"); p=&a[0]; /* first pointer points 0th element */ for(i=0;i<n;i++) { s=&a[i]; /* second pointer points every element one by one */ if(*p>*s) /* if first is bigger than second */ *p=*s; /* first becomes second */ s++; /* second is incremented to check with other elements */ } printf("smallest digit in array is %dn",*p); getch(); }
  • 45. ---------------------------------------------------------------------------------------------------------------- (d) Write a program which performs the following tasks: − initialize an integer array of 10 elements in main( ) − pass the entire array to a function modify( ) − in modify( ) multiply each element of array by 3 − return the control to main( ) and print the new array elements in main( ) Solution: #include<stdio.h> #include<conio.h> void main() { int i,j,a[10]={1,2,3,4,5,6,7,8,9,10}; modify(); clrscr(); printf("array before modification: nn"); for(i=0;i<10;i++) { printf(" %d ",a[i]); }
  • 46. modify(a); /* passing only the name of array */ printf("nnnarray after modification:nn"); for(i=0;i<10;i++) { /* printing the array in main(); */ printf(" %d ",a[i]); } getch(); } modify(int b[10]) { int c; for(c=0;c<10;c++) { b[c]=b[c]*3; /* multiplying each element with 3 */ } return b[c]; /* returning the whole array to main(); */ } ---------------------------------------------------------------------------------------------------------- (e) The screen is divided into 25 rows and 80 columns. The characters that are displayed on the screen are
  • 47. stored in a special memory called VDU memory (not to be confused with ordinary memory). Each character displayed on the screen occupies two bytes in VDU memory. The first of these bytes contains the ASCII value of the character being displayed, whereas, the second byte contains the colour in which the character is displayed. For example, the ASCII value of the character present on zeroth row and zeroth column on the screen is stored at location number 0xB8000000. Therefore the colour of this character would be present at location number 0xB8000000 + 1. Similarly ASCII value of character in row 0, col 1 will be at location 0xB8000000+ 2, and its colour at 0xB8000000 + 3. With this knowledge write a program which when executed would keep converting every capital letter on the screen to small case letter and every small case letter to capital letter. The procedure should stop the moment the user hits a key from the keyboard. This is an activity of a rampant Virus called Dancing Dolls. (For monochrome adapter, use 0xB0000000instead of 0xB8000000). Solution: _______________________________________________________________________
  • 48. Exercise [L] (a) How will you initialize a three-dimensional array threed[3][2][3]? How will you refer the first and last element in this array? Solution: #include<stdio.h> #include<conio.h> void main() { /* initialization of a 3 dimensional array */ int threed[3][2][3]={ { {100,2,3}, {1,2,3} }, { {8,5,6}, {4,5,6} }, { {7,8,9}, {7,8,200} } }; int *f,*l; clrscr();
  • 49. f=&threed[0][0][0]; /* reference to first element */ l=&threed[2][1][2]; /* reference to second element */ printf("nnfirst element = %d",*f); printf("nnlast element = %d",*l); getch(); } --------------------------------------------------------------------------------------------------------------- (b) Write a program to pick up the largest number from any 5 row by 5 column matrix. Solution: #include<stdio.h> #include<conio.h> void main() { int i,j,a[5][5]; clrscr(); printf("nType the numbers to in matrix:n");
  • 50. for(i=0;i<5;i++) { for(j=0;j<5;j++) { scanf("%d",&a[i][j]); } } clrscr(); printf("matrix you entered is:nn"); for(i=0;i<5;i++) { for(j=0;j<5;j++) { printf(" %2d ",a[i][j]); } printf("n"); } /* finding the largest number */ for(i=0;i<5;i++) { for(j=0;j<5;j++) { if(a[0][0]<a[i][j]) /* if number is larger than first element */
  • 51. a[0][0]=a[i][j]; /* larger number is placed as the first element */ } } printf("nnThe largest number in matrix is: %d",a[0][0]); getch(); } --------------------------------------------------------------------------------------------------------------- (c) Write a program to obtain transpose of a 4 x 4 matrix. The transpose of a matrix is obtained by exchanging the elements of each row with the elements of the corresponding column. Solution: #include<stdio.h> #include<conio.h> #define MAX 4 void main() {
  • 52. int i,j,a[4][4],b[4][4]; clrscr(); printf("nenter numbers in 5x5 matrix: nn"); for(i=0;i<MAX;i++) { for(j=0;j<MAX;j++) { scanf("%d",&a[i][j]); } } clrscr(); printf("nmatrix you entered is: nn"); for(i=0;i<MAX;i++) { for(j=0;j<MAX;j++) { printf("%2d ",a[i][j]); } printf("n"); } /* transpose of matrix */
  • 53. for(i=0;i<MAX;i++) { for(j=0;j<MAX;j++) { b[j][i]=a[i][j]; } } printf("nn"); /* printing the transpose */ printf("Transpose of matrix is: nn"); for(i=0;i<MAX;i++) { for(j=0;j<MAX;j++) { printf("%2d ",b[i][j]); } printf("n"); } getch(); } ----------------------------------------------------------------------------------------------------------------
  • 54. (d) Very often in fairs we come across a puzzle that contains 15 numbered square pieces mounted on a frame. These pieces can be moved horizontally or vertically. A possible arrangement of these pieces is shown below: 1 4 15 7 8 10 2 11 14 3 6 13 12 9 5 As you can see there is a blank at bottom right corner. Implement the following procedure through a program: Draw the boxes as shown above. Display the numbers in the above order. Allow the user to hit any of the arrow keys (up, down, left, or right). If user hits say, right arrow key then the piece with a number 5 should move to the right and blank should replace the original position of 5. Similarly, if down arrow key is hit, then 13 should move down and blank should replace the original position of 13. If left arrow key or up arrow key is hit then no action should be taken. The user would continue hitting the arrow keys till the numbers aren’t arranged in ascending order.
  • 55. Keep track of the number of moves in which the user manages to arrange the numbers in ascending order. The user who manages it in minimum number of moves is the one who wins. How do we tackle the arrow keys? We cannot receive them using scanf( ) function. Arrow keys are special keys which are identified by their ‘scan codes’. Use the following function in your program. It would return the scan code of the arrow key being hit. Don’t worry about how this function is written. We are going to deal with it later. The scan codes for the arrow keys are: up arrow key – 72 down arrow key – 80 left arrow key – 75 right arrow key – 77 /* Returns scan code of the key that has been hit */ #include "dos.h" getkey( ) { union REGS i, o ; while ( !kbhit( ) ) ; i.h.ah = 0 ; int86 ( 22, &i, &o ) ; return ( o.h.ah ) ; }
  • 56. Solution: #include<stdio.h> #include<conio.h> #include<dos.h> /* returns scan code of the key that has been hit */ getkey() { union REGS i,o; while(!kbhit() ) ; i.h.ah=0; int86(22,&i,&o); return(o.h.ah); } void main() { int i,j,a[16]={1,4,15,7,8,10,2,11,14,3,6,13,12,9,5,0}; int temp,h,moves=0,won=0; clrscr(); /****************************************************/ do { /**************/
  • 57. /* to move up */ /**************/ if(h==72) { for(i=0;i<16;i++) { if(a[i]==0){ if(a[0]==0 || a[1]==0 || a[2]==0 || a[3]==0) { break; } temp=a[i]; a[i]=a[i-4]; a[i-4]=temp; moves=moves+1; break; } } } /****************/ /* to move left */ /****************/ if(h==75) { for(i=0;i<16;i++) { if(a[i]==0){ if(a[0]==0 || a[4]==0 || a[8]==0 || a[12]==0) { break; } temp=a[i];
  • 58. a[i]=a[i-1]; a[i-1]=temp; moves=moves+1; break; } } } /****************/ /* to move down */ /****************/ if(h==80) { for(i=0;i<16;i++) { if(a[i]==0){ if(a[12]==0 || a[13]==0 || a[14]==0 || a[15]==0) { break; } temp=a[i]; a[i]=a[i+4]; a[i+4]=temp; moves=moves+1; break; } } } /*****************/ /* to move right */ /*****************/ if(h==77) {
  • 59. for(i=0;i<16;i++) { if(a[i]==0) { if(a[3]==0 || a[7]==0 || a[11]==0 || a[15]==0 ) { break; } temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; moves=moves+1; break; } } } /***********************************************************/ /**********************************/ /* printing the puzzle with boxes */ /**********************************/ printf("n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%cn",218,196,196,196,194,196,196,196,194, 196,196,196,194,196,196,196,191); for(i=0;i<=15;i++) { printf("%c",179); if(a[i]==0) { printf("%c ",32); /* printing a blank space in the puzzle */ }
  • 60. if(a[i]!=0) printf(" %2d",a[i]); if(a[i]==a[3] || a[i]==a[7] || a[i]==a[11] || a[i]==a[15]) printf("%c",179); if(i==3||i==7||i==11) printf("n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%cn",195,196,196,196,197,196,196,196,197, 196,196,196,197,196,196,196,180); if(a[0]==1 && a[1]==2 && a[2]==3 && a[3]==4 && a[4]==5 && a[5]==6 &&a[6]==7 && a[7]==8 && a[8]==9 && a[9]==10 && a[11]==12 && a[12]==13 && a[13]==14 && a[14]==15 && a[15]==0 ) { won=1; } } printf("n%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%cn",192,196,196,196,193,196,196,196,193, 196,196,196,193,196,196,196,217); /***************************************************/ if(won==1) { printf("nntCongratulations! you have won."); break; } /**********************************/ /* to print instructions for user */ /**********************************/ printf("nnnnnn Total Moves: %dtttt Use arrow keys to move blank:nn",moves);
  • 61. printf("tttttt %c to move upn",30); printf("tttttt %c to move downn",31); printf("tttttt %c to move leftn",17); printf("tttttt %c to move rightn",16); /****************************************************/ /**********************/ /* to take user input */ /**********************/ h=getkey(); clrscr(); /****************************************************/ }while(h==72 || h==75 || h==77 ||h==80); getch(); } ----------------------------------------------------------------------------------------------------------------- (e) Those readers who are from an Engineering/Science background may try writing programs for following problems. (1) Write a program to add two 6 x 6 matrices.
  • 62. (2) Write a program to multiply any two 3 x 3 matrices. (3) Write a program to sort all the elements of a 4 x 4 matrix. (4) Write a program to obtain the determinant value of a 5 x 5 matrix. Solution: -------------------------------------------------------------------------------------------------------------- (j) Write a program that interchanges the odd and even components of an array. Solution: #include<stdio.h> #include<conio.h> void main() { int i,j,a[6],even,temp; clrscr(); printf("enter the numbers: nn"); for(i=0;i<6;i++) { scanf("%d",&a[i]);
  • 63. } clrscr(); printf("narray without exchanging even and odd numbers:nn"); for(i=0;i<6;i++) { printf("%2d ",a[i]); } printf("nnarray after exchanging even and odd numbers: nn"); for(i=0;i<6;i++) { for(j=i+1;j<6;j++) { /* if one element is even and another after that is odd ,they will be exchanged */ if((a[i]%2)!=0 && (a[j]%2)==0) { temp=a[j]; a[j]=a[i]; a[i]=temp; } } } for(i=0;i<6;i++) {
  • 64. printf("%2d ",a[i]); } getch(); } -------------------------------------------------------------------------------------------------------------- (k) Write a program to find if a square matrix is symmetric. Solution: #include<stdio.h> #include<conio.h> void main() { int i,j,r,c,sym; int a[100][100],b[100][100]; clrscr(); printf(" enter number of rows of matrix: "); scanf("%d",&r); printf("nnenter number of columns of matrix: "); scanf("%d",&c);
  • 65. clrscr(); printf("enter the elements in matrix: n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } clrscr(); printf("nmatrix you entered isnn"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d ",a[i][j]); } printf("n"); } printf("nntranspose of matrix is nn"); for(i=0;i<r;i++) {
  • 66. for(j=0;j<c;j++) { b[j][i]=a[i][j]; } } for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d ",b[i][j]); } printf("n"); } /* finding if square matrix is equal to it's transpose to be symmetric */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { if(a[i][j]!=b[i][j]) sym=1; } }
  • 67. if(sym==1) printf("nSquare matrix is not symmetric.n"); else printf("nSquare matrix is symmetric.n"); getch(); } ---------------------------------------------------------------------------------------------------------------- (l) Write a function to find the norm of a matrix. The norm is defined as the square root of the sum of squares of all elements in the matrix. Solution: #include<stdio.h> #include<conio.h> #include<math.h> void main() { int i,j,r,c,a[100][100]; int norm=0,sum=0; clrscr(); printf("nEnter the number of rows: "); scanf("%d",&r);
  • 68. printf("nnEnter the number of coloumns: "); scanf("%d",&c); clrscr(); printf("Enter elements of %d x %d array: nn",r,c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } clrscr(); printf("nmatrix you entered is: nn"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%2d ",a[i][j]); } printf("n"); } /* norm of the matrix */
  • 69. for(i=0;i<r;i++) { for(j=0;j<c;j++) { sum=sum+(a[i][j]*a[i][j]); } } norm=sqrt(sum); printf("nNorm of matrix = %d",norm); getch(); } ---------------------------------------------------------------------------------------------------------------- (m) Given an array p[5], write a function to shift it circularly left by two positions. Thus, if p[0] = 15, p[1]= 30, p[2] = 28, p[3]= 19 and p[4] = 61 then after the shift p[0] = 28, p[1] = 19, p[2] = 61, p[3] = 15 and p[4] = 30. Call this function for a (4 x 5 ) matrix and get its rows left shifted. Solution: #include<stdio.h>
  • 70. #include<conio.h> void main() { int i,j,p[]={15,30,28,19,61}; int a[4][5]; clrscr(); printf("Array before shift:nn"); for(i=0;i<5;i++) { printf("%2d ",p[i]); } func(p); printf("nnArray after shift:nn"); for(i=0;i<5;i++) { printf("%2d ",p[i]); } printf("nnnenter the elements of 4x5 matrix: nn"); for(i=0;i<4;i++) { for(j=0;j<5;j++) {
  • 71. scanf("%d",&a[i][j]); } } clrscr(); printf("matrix you enterd before shift: nn"); for(i=0;i<4;i++) { for(j=0;j<5;j++) { printf("%2d ",a[i][j]); } printf("n"); } printf("nnafter shift:nn"); /* shift the rows of matrix */ for(i=0;i<4;i++) { func(a[i]); }
  • 72. for(i=0;i<4;i++) { for(j=0;j<5;j++) { printf("%2d ",a[i][j]); } printf("n"); } getch(); } func(int q[5]) { int a,t1,t2,t3; t1=q[0]; t2=q[1]; q[0]=q[2]; q[1]=q[3]; q[2]=q[4]; q[3]=t1; q[4]=t2; return q[5]; }
  • 73. ---------------------------------------------------------------------------------------------------------- (n) A 6 x 6 matrix is entered through the keyboard and stored in a 2-dimensional array mat[7][7]. Write a program to obtain the Determinant values of this matrix. Solution: ---------------------------------------------------------------------- -------- (o) For the following set of sample data, compute the standard deviation and the mean. -6, -12, 8, 13, 11, 6, 7, 2, -6, -9, -10, 11, 10, 9, 2 Solution: #include<stdio.h> #include<conio.h> #include<math.h> void main() { int a[15]={-6,-12,8,13,11,6,7,2,-6,-9,-10,11,10,9,2}; int i,j; float temp,sd,sum=0,mean,x; clrscr();
  • 74. printf("ndata set: nn"); for(i=0;i<15;i++) { printf(" %3d ",a[i]); } printf("n"); for(i=0;i<15;i++) { sum=sum+a[i]; /* adding all the numbers */ } mean=sum/15; /* calculating the mean */ /* computing standard deviation */ for(i=0;i<15;i++) { a[i]=pow((a[i]-mean),2); x=x+a[i]; } temp=x/15; sd=sqrt(temp);
  • 75. printf("nnttmean= %fnttstandard deviation = %fn",mean,sd); getch(); } -------------------------------------------------------------------------------------------------------------- (p) The area of a triangle can be computed by the sine law when 2 sides of the triangle and the angle between them are known. Area = (1 / 2 ) ab sin ( angle ) Given the following 6 triangular pieces of land, write a program to find their area and determine which is largest, Plot No. a b angle 137.4 80.9 0.78
  • 77. 120.0 1.75 Solution: #include<stdio.h> #include<conio.h> #include<math.h> void main() { float a[6][3]={ {137.4, 80.9, 0.78}, {155.2, 92.62, 0.89}, {149.3, 97.93, 1.35}, {160.0, 100.25, 9.00}, {155.6, 68.95, 1.25}, {149.7, 120.0, 1.75} }; float big=0,area; int sr=0,i; clrscr(); for(i=0;i<6;i++) { area=(1.0/2.0)*a[i][0]*a[i][1]*sin(a[i][2]); if(area>big) { big=area; sr=i;
  • 78. } } printf("nnPlot no. %d is the biggest.n",sr); printf("nArea of plot no. %d = %fn",sr,big); getch(); } - ------------------------------------------------------------------------------------------------------------ (q) For the following set of n data points (x, y), compute the correlation coefficient r, x y 34.22 102.43 39.87
  • 80. 40.71 94.85 55.15 94.65 Solution: #include<stdio.h> #include<conio.h> #include<math.h> void main() { float a[][2]={ {34.22,102.43}, {39.87,100.93}, {41.85,97.43}, {43.23,97.81}, {40.06,98.32}, {53.29,98.32}, {53.29,100.07}, {54.14,97.08}, {49.12,91.59}, {40.71,94.85}, {55.15,94.65} }; int i,n=0; float x2,y2,x,y,x_y,n_x2,n_y2,r;
  • 81. clrscr(); for(i=0;i<11;i++) { x2= x2 + ( a[i][0] * a[i][0] ); /* computing square of x */ y2= y2 + ( a[i][1] * a[i][1] ); /* computing square of y */ x= x + a[i][0]; /* computing total of x */ y= y + a[i][1]; /* computing total of y */ x_y= x_y + ( a[i][0] * a[i][1] ); /* computing total of x * y */ n++; } n_x2= n * x2; n_y2= n * y2; r= ( x_y - x*y )/sqrt((n_x2-x2) * (n_y2-y2)); printf(" sum of square of x = %fnn",x2); printf(" sum of square of y = %fnn",y2); printf(" sum of x = %fnn",x); printf(" sum of y = %fnn",y); printf(" sum of x * y = %fnn",x_y); printf(" sum of n*x2 = %fnn",n_x2); printf(" sum of n*y2 = %fnn",n_y2);
  • 82. printf("nnnCorrelation cofficient = %fn",r); getch(); } ------------------------------------------------------------------------------------------------------------- (r) For the following set of point given by (x, y) fit a straight line given by y = a + bx x y 3.0 1.5 4.5 2.0 5.5 3.5
  • 84. #include<math.h> void main() { float data[][2]= { {3.0,1.5}, {4.5,2.0}, {5.5,3.5}, {6.5,5.0}, {7.5,6.0}, {8.5,7.5}, {8.0,9.0}, {9.0,10.5}, {9.5,12.0}, {10.0,14.0} }; int i,n=0; float sx,sy,x2,y2,xy,a,b,Y; clrscr(); for(i=0;i<10;i++) { sx = sx + data[i][0]; sy = sy + data[i][1]; x2= x2 + ( data[i][0] * data[i][0] ); y2= y2 + ( data[i][1] * data[i][1] ); xy = xy + ( data[i][0] * data[i][1] );
  • 85. n++; } printf(" sum of x = %fn",sx); printf(" sum of y = %fn",sy); printf(" sum of x2 = %fn",x2); printf(" sum of y2 = %fn",y2); printf(" sum of x*y = %fn",xy); printf(" total number = %dn",n); b = ( (n*xy) - (sx*sy) ) / ( n*x2 - (sx*sx) ); a = (sy/n) - b*(sx/n); Y= a + b*sx ; printf("nnvalue of a = %fnn",a); printf("value of b = %fnn",b); printf(" Y = %f nn",Y); getch(); } -------------------------------------------------------------------------------------------------------------
  • 86. (s) The X and Y coordinates of 10 different points are entered through the keyboard. Write a program to find the distance of last point from the first point (sum of distance between consecutive points). Solution: #include<stdio.h> #include<conio.h> void main() { float a[10][2],sx,sy; int i; clrscr(); for(i=0;i<10;i++) { printf("Enter coordinates of point number %d:nn",i+1); printf("Value of X coordinate: "); scanf("%f",&a[i][0]); printf("nValue of Y coordinate: "); scanf("%f",&a[i][1]);
  • 87. clrscr(); } for(i=0;i<10;i++) { if(i>0 && i<10-1) { sx = sx + a[i][0]; sy = sy = a[i][1]; } } printf(" First coordinate: X = %ftY = %fnn",a[0][0],a[0][1]); printf(" Last coordinate: X = %ftY = %fnn",a[9][0],a[9][1]); printf("nDistance between them: X = %ftY = %fn",sx,sy); getch(); }