akashmagrawal akashmagrawal - 3 months ago 10
C Question

Error While taking the input

Hey I don't understand why my its taking two inputs while taking the element as input . I tried this code on TurboC compiler , GCC but got the same error .

#include <stdio.h>


int menu();
void bubble_short();
void selection_short();

int main()
{
int ch,j,n,a[100];

ch=menu();

switch (ch)
{
case 1:
{
bubble_short();
break;
}
case 2:
{
selection_short();
}
default :
break;
}
}

void bubble_short()
{
int i,j,n,a[100];
printf("Elements");
scanf("%d",&n);
for (j=0; j<n;j++)
{
scanf("%d",&a[j]);
}
for (i=0;i<n;i++)
{
for (j=0;j<n-1-i;j++)
{
if (a[j]>a[j+1])
{
a[j]=a[j]+a[j+1];
a[j+1]=a[j]-a[j+1];
a[j]=a[j]-a[j+1];
}
}
}

printf("the sorted elements are :\n");
for ( i = 0; i < n; i++)
{
printf("%d\n",a[i]);
}
}


void selection_short()
{
int i,j,n,a[100],min;
printf("Elements");
scanf("%d",&n);
for ( i = 0; i <n-1; ++i)
{
min=i;
for ( j = 1+i; i < n; ++i)
{
if(a[min]>a[j])
min=j;
}
if(i!=min)
{
a[i]=a[i]+a[min];
a[min]=a[i]-a[min];;
a[i]=a[i]-a[min];;
}
}

printf("the shorted elements are :\n");
for ( i = 0; i < n; ++i)
{
printf("%d\n",a[i] );
}
}

int menu()
{
int k;
printf("Enter the choice \n 1. bubble short \n 2. selectionshort");
scanf("\n %d ",&k);
return k;
}


Hey I don't understand why my it's taking two inputs while taking the element as input. I tried this code on TurboC compiler, GCC but got the same error.

Output

enter image description here

Answer

Got your problem!

Never use newlines, whitespace, tabs and return carriages inside scanf as to avoid such problems and maintaining good coding guidelines! These act as delimiters for it and you have provided 3 of them.

Edit your menu scanf to this:-

 scanf("%d",&k);

A basic logic behind it:- Taking a basic example :-

scanf("%d %d", &i, &j);

Notice that space between two placeholders. When you run this, it will take the first input and then it will wait for that delimiter to be read from the keyboard and afterwards it will read the second parameter of the input.

I think the rest of the program should run fine.

Comments