write a c program to insert values into an array without pressing enter key after each digit....


#include<stdio.h>


int sumdig();

void main()
{
clrscr();
printf("Summation is : %d",sumdig());
getch();
}


int sumdig()
{
int s=0,i=0,ar[10],j;
char ch;
printf("Enter the values: ");
while(1)
{
ch=getche();
if(ch==13)
break;

ar[i++]=ch-'0';
}
for(j=0;j<i;j++)
{
s=s+ar[j];
}
clrscr();
return s;
}



input: Enter the values : 231

output: Summation is : 6



result analysis:    while(1) means the loop will be executed infinite times if we don't put any stop condition. It will take one element from the keyboard and put them into a character variable called 'ch'. Here 0,1,2 ....9 ... will be treated as character. To convert them into integer we need to subtract ASCII value of the '0' from the character. (ie. ASCII value of '1' is 49 . If we subtract ASCII value of '0' means 48 from 49 it will give integer 1.)This integer value will be stored into array until you press enter key [if(ch==13)]. The rest part is same as summation of each element of an array. 

Comments

Popular posts from this blog

Pascal Triangle using 2D array

JAVA program to add two distance