-4

i have wrote a program to sum int array but i want if one input is string(character) then the program will give error "You Must Enter Int value".

my following code:

#include <stdio.h>


 int main()
    {
int a[1000],i,n,sum=0;
    

printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
    scanf("%d",&a[i]);
}

for(i=0; i<n; i++)
{
     
    sum+=a[i];
}

    printf("sum of array is : %d",sum);     

         return 0;
      }
Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
Mac
  • 74
  • 1
  • 11

4 Answers4

2

scanf() returns the number of successfully matched input items. So, check if scanf() returns 1.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

create a while loop in that take user input and check that is it an int if yes then break; or continue the loop printing"Enter an Integer" check it is int or not by int c = scanf("%d",&a[]) if c == 1 then input is Integer or it is not an integer

Check if input is integer type in C

#include <stdio.h>

    int main()
    {
    int a[1000],i,n,sum=0;


    printf("Enter size of the array : ");
    scanf("%d",&n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        if(scanf("%d",&a[i]) != 1){
            printf("you must enter a int number");
       }
    }

    for(i=0; i<n; i++)
    {

    sum+=a[i];
    }

    printf("sum of array is : %d",sum);

    return 0;
    }
  • can u please write the full code solution because im new in C so please. – Mac Sep 11 '20 at 16:09
  • Debashish biswas i appreciate your efforts, but i want a program in which if i enter a character input it should give an error "you must enter a int number" i think it can be done with if/else.... – Mac Sep 11 '20 at 16:21
  • check the code that i have include after edit the answer. i hope it will work – Debasish Biswas Sep 11 '20 at 16:29
0
 #include<stdio.h> 
int main()
 {
int a[1000],i,n,sum=0;

printf("Enter size of the array : ");
scanf("%d",&n);

printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
    scanf("%d",&a[i]);
}


for(i=0; i<n; i++)
{
     
    sum+=a[i];
}
 printf("sum of array is : %d",sum);

return 0;

}

  • 1)Read the array size and store it in the variable n. 2) Scanf function reads the entered element and store the element in to the array as a[i] using for(i=0;i – Danesh Muthu Krisnan Sep 11 '20 at 16:30
0
#include <stdio.h>


 int main()
    {
int a[1000],i,n,sum=0;
    

printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
    //scanf() return 0 if input is not valid
    if(scanf("%d",&a[i]) == 0)
    {
       printf("error");
       return;  //or use exit(0)
      
    }
}

for(i=0; i<n; i++)
{
     
    sum+=a[i];
}

    printf("sum of array is : %d",sum);     

         return 0;
      }
Sathvik
  • 565
  • 1
  • 7
  • 17