Counting arguments passed to scanf() in C - c

Is there any way to Count number of arguments passed to scanf() in C ? Specially, while assigning int arrays through scanf().
Example:
int array[1000], i;
for(i=0;i<1000;i++)
scanf("%d",&array[i]);
I need to count how many values are inserted by user

I don't think there's a built in way to do this, but why not just create a counter that increments when scanf returns successfully and break the loop otherwise?
int scanf_counter = 0;
int array[1000], i;
for(i=0;i<1000;i++) {
if(scanf("%d",&array[i] > 0) {
scanf_counter++;
} else {
break;
}
}
Although I'm not sure I understand your question exactly because you could always just find the size of the array by doing this
int size = sizeof(array)/sizeof(array[0])

Look the scanf() fragment carefully, thus:
include
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}

Related

Loop until the correct data type is inputted using C [duplicate]

I need help with error checking for my program. I'm asking the user to input a integer and I would like to check if the users input is a integer. If not, repeat the scanf.
My code:
int main(void){
int number1, number2;
int sum;
//asks user for integers to add
printf("Please enter the first integer to add.");
scanf("%d",&number1);
printf("Please enter the second integer to add.");
scanf("%d",&number2);
//adds integers
sum = number1 + number2;
//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);
//checks if sum is divisable by 3
if(sum%3 == 0){
printf("The sum of these two integers is a multiple of 3!\n");
}else {
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}
scanf returns the count of items that it has successfully read according to your format. You can set up a loop that exits only when scanf("%d", &number2); returns 1. The trick, however, is to ignore invalid data when scanf returns zero, so the code would look like this:
while (scanf("%d",&number2) != 1) {
// Tell the user that the entry was invalid
printf("You did not enter a valid number\n");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}
Since you read a number more than once in your code, consider making a function to hide this loop, and call this function twice in your main to avoid duplication.
Here is a solution of your problem. I just modified some of your code.
Read comments for any explanations.
#include<stdio.h>
#include<stdlib.h> //included to use atoi()
#include<ctype.h> //included to use isalpha()
#define LEN 3 //for two digit numbers
int main(void)
{
char *num1=malloc(LEN);
char *num2=malloc(LEN);
int i,flag=0;
int number1,number2;
int sum;
do
{
printf("Please enter the first integer to add = ");
scanf("%s",num1);
for (i=0; i<LEN; i++) //check for every letter of num1
{
if (isalpha(num1[i])) //isalpha(num1[i]) returns true if num1[i] is alphabet
{ //isalpha() is defined in ctype.h
flag=1; //set flag to 1 if num1[i] is a alphabet
}
}
if(flag)
{
printf("Not a valid Integer\n");
flag=0;
continue;
}
else
{
break;
}
} while(1);
do
{
printf("Please enter the second integer to add = ");
scanf("%s",num2);
for (i=0; i<LEN; i++)
{
if (isalpha(num2[i]))
{
flag=1;
}
}
if(flag)
{
printf("Not a valid Integer\n");
flag=0;
continue;
}
else
{
break;
}
} while(1);
//strings to integers
number1= atoi(num1); //atoi() is defined in stdlib.h
number2= atoi(num2);
//adds integers
sum = number1 + number2;
//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);
//checks if sum is divisable by 3
if(sum%3 == 0)
{
printf("The sum of these two integers is a multiple of 3!\n");
}
else
{
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}
I designed this for only two digit numbers, but it is working fine for more than two digit numbers for me.
Please let me know that same is happening in your case.
And if you will find why this is happening please comment.
And you can also use strtol() instead of atoi(). I am not using it because of small values.
Difference between atoi() and strtol()
atoi()
Pro: Simple.
Pro: Convert to an int.
Pro: In the C standard library.
Pro: Fast.
Con: No error handling.
Con: Handle neither hexadecimal nor octal.
strtol()
Pro: Simple.
Pro: In the C standard library.
Pro: Good error handling.
Pro: Fast.
Con: Convert to a long, not int which may differ in size.
I would like to say that you have to make some custom validation to check if whether scanf read integer or not.I am used fgets not interested in scanf.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int validate ( char *a )
{
unsigned x;
for ( x = 0; x < strlen ( a ); x++ )
if ( !isdigit ( a[x] ) ) return 1;
return 0;
}
int main ( void )
{
int i;
char buffer[BUFSIZ];
printf ( "Enter a number: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
buffer[strlen ( buffer ) - 1] = '\0';
if ( validate ( buffer ) == 0 ) {
i = atoi ( buffer );
printf ( "%d\n", i );
}
else
printf ( "Error: Input validation\n" );
}
else
printf ( "Error reading input\n" );
return 0;
}
A clean approach to this problem can be
read from stdin using fgets().
use strtol() to convert and store the value into an int. Then check for the char **endptr to determine whether the conversion is success [indicates integer] or not.
Perform remaining task.

C Loop until the condition is met problem

I want to write a loop that runs until the user enters a number greater than 10, but I have to do something wrong because it creates an infinite loop.
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
for(int i=0;a<10;i++){
printf("Enter value>10");
i++;
printf("%d",&a);
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
You mix an index that does not make sense. Also you print the memory address of variable instead of its value, not sure it is what you wanted?
Code partially corrected (because I don't know what is your ultimate goal):
#include <stdio.h>
int main()
{
int a;
do {
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
printf("\na: %d\n",a);
} while (a <= 10);
printf("Result:%d\n",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
ps: \n is line return and added do while which is what you want when you want to execute a loop at least once.
Have a look at your for-loop: you let i start at zero, you continue until a is not smaller than ten anymore, but it's not the value of a you need to check, it's the one of i.
In top of that, you are doing a i++ within your for-loop, while this is already covered in the definition of the for-loop.
I think this is the code that you are looking for: See comments
#include <stdio.h>
int main()
{
int a, ok = 0, end_of_input = 0;
do {
printf("Please input an integer value (min. 10): ");
fflush(stdout); // So the user can see the above line!
switch(scanf("%d",&a)) {
case EOF: // End of input - Give up!
end_of_input = 1;
break;
case 1: // Got a number - Check it!
if (a < 10)
{
ok = 1;
} else {
printf("%d - Not appropriate input. Please try again.\n\n",a);
}
break;
default: // Summat else - "eat" the input to the next line
scanf("%*[^\n]\n"); // "eats" the rest of the line in the buffer w/o assignment
break;
}
} while (end_of_input == 0 || ok == 0);
if (ok) { // User entered a valid number
printf("Got a that is smaller than ten %d\n", d);
} else { // We have ran out of input
printf("See you want to leave us :-(\n");
}
return 0;
}
I am not sure what you are trying to achieve but one problem that I found in your logic is you prompting user for input outside the loop. So whenever you enter number less than 10 it always goes in infinite iteration.
Try following code, with scanf inside loop
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
int i=0;
for(;a<10;){
printf("Enter value>10");
scanf("%d",&a);
printf("%d",a);
i++;
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}

program that does not terminate

I wrote a program that should take an array of numbers and find the array index of the smallest number. However, when I type the numbers with spaces between and then press enter, the program keeps running. What can be the cause? Here is the code:
#include<stdio.h>
//read numbers to an array
//find minimum
//print the index of minimum
double findMinimum(int size,double array[]){
int n;
int minIndex=0;
for(n=1;n<size;size++){
if(array[n]<array[n-1]){
minIndex=n;
}
}
return minIndex;
}
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
double inArray[size];
printf("Enter an array of numbers:");
int k=0;
char c;
while(c!='\n'){
c=getchar();
if(c=='\n'){
break;
}
scanf("%lf",&inArray[k]);
k++;
size++;
};
int minIndex=0;
minIndex=findMinimum(size,inArray);
printf("The index of minimum number is %i",minIndex);
return 0;
}
I also took the part of the code that scans numbers to an array. I tried to change the while loop and used "break" statement, but the output gave all numbers in an array except the first one. Here is the code:
#include<stdio.h>
//read numbers to an array
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
double inArray[size];
printf("Enter an array of numbers ending with question mark:\n");
int k=0;
char c;
while(1){
c=getchar();
if(c=='?'){
break;
}
scanf("%lf",&inArray[k]);
k++;
size++;
};
int n;
for(n=0;n<size;n++){
printf("%f\n",inArray[n]);
}
return 0;
}
Thanks for help in advance!
for(n=1;n<size;size++){
if(array[n]<array[n-1]){
minIndex=n;
}
}
The issue in your code is you are incrementing size, thats why your loop is not terminating. increment n
Edit
you have initialized your 'n' with 1 , however arrays start with zero index thats why it misses the first element,
for(n=0;n<size;n++){
if(array[n]<array[minIndex]){
minIndex=n;
}
}
try this one :
for(n=1; n < size; n++){
if(array[n]<array[minIndex]){
minIndex=n;
}
}

C program not reaching For loop

I'm currently trying to write a C program using the NetBeans IDE.The goal is to take input from the user on the amount of sticks they want drawn on the screen where the Letter "I' is a stick as noted in the for loops. The thing is, I use scanf to get the user input for each row , but the program executes and runs but never actually seems to reach the for loop, since it doesn't do any of the print statements within it. My IDE doesn't print any of my print statements in the for-loops, which is why I'm assuming it isn't reaching them.
I have tried simply assuming values for user input, instead of using scanf, but that also does not seem to reach the for loop. Any input on what I could do to fix this, would be much appreciated!
#include <stdio.h>
int main(void) {
int length1, length2, length3;
int inputRow1, inputRow2, inputRow3;
printf("Please enter the number of Sticks you would like per row\n");
scanf("%d%d%d", inputRow1, inputRow2, inputRow3);
for (length1 = 0; length1 < inputRow1; length1++) {
printf("I");
for (length2 = 0; length2 < inputRow2; length2++) {
printf("I");
for (length3 = 0; length3 < inputRow3; length3++) {
printf("I");
return (0);
}
}
}
}
While using scanf you should store the values in the variables using &.
Change
scanf("%d%d%d",inputRow1,inputRow2,inputRow3);
to
scanf("%d%d%d",&inputRow1,&inputRow2,&inputRow3);
And your return statement should be before exiting from the main().
For example:
#include <stdio.h>
int main()
{
int length1,length2,length3;
int inputRow1,inputRow2,inputRow3;
printf("Please enter the number of Sticks you would like per row\n");
scanf("%d%d%d",&inputRow1,&inputRow2,&inputRow3);
for(length1=0;length1<inputRow1; length1++)
{
printf("I");
for(length2=0;length2<inputRow2;length2++)
{
printf("I");
for(length3=0;length3<inputRow3;length3++)
{
printf("I");
}
printf("\n");
}
printf("\n");
}
printf("\n");
return(0);
}

how to find array element from user input

friend i am new in c ,so i face problem in a ,code, plz if there is any wrong in my logic,take it as a pardon eye,
I am trying to find the element in a two dimensional array, so i have declare a two dimensional array in my code, i will take a user input, the input will compare with data in an full array a column index of two dimensional array, if any data found similar of that column index then it will give the same row data of another column of array. if i give a input in my code it is giving output of the number is not in array index, though the number is in the array index, so i dont understand where is my fault.
plz help me to fix the problem.
here is my code :
#include<stdio.h>
int main()
{
int arr[10][3]={{1,5},
{2,8},
{3,27},
{ 4,64},
{5,125},
{6,216},
{ 7,343},
{8,512},
{ 9,729},
{ 10,1000}};
int i, num;
printf("Enter a number\n");
scanf("%d",&num);
for(i=0;i<10;i++)
{
if (num==arr[i][0])
printf("%d",arr[i][1]);
break;
}
if (num==10)
printf("the number is not there");
return 0;
}
You have an errant semi-colon:
if (num==10);
printf("the number is not there");
That call to printf will run each time because there is no body for the if statement. With better formatting:
if (num==10);
printf("the number is not there");
As #zoska points out, you also have the same bug here:
if (num==arr[i][0]);
I would do the following three changes at the minimum:
Change int arr[10][3] to int arr[10][2]
Change
if (num==arr[i][0]);
printf("%d",arr[i][1]);
to
if (num == arr[i][0]) {
printf("%d",arr[i][1]);
}
Change
if (num==10);
printf("the number is not there");
to
if (i == 10) { // note: 'num' changed to 'i'
printf("the number is not there");
}
Your code should look like this in the future
#include <stdio.h>
int main(void)
{
int arr[10][2] = {
{1,5},
{2,8},
{3,27},
{4,64},
{5,125},
{6,216},
{7,343},
{8,512},
{9,729},
{10,1000}
};
int i, num;
printf("Enter a number\n");
scanf("%d", &num);
for(i = 0; i < 10; i++)
{
if (num==arr[i][0]) {
printf("%d", arr[i][1]);
break;
}
}
if (i == 10) {
printf("the number is not there");
}
return 0;
}

Resources