Execution of a for loop [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How will this loop be executed infinite times?
#include <stdio.h>
int main() {
int i;
for (; scanf("%d", &i); printf("%d\n", i));
return 0;
}

Condition part of for loop is scanf("%d", &i); which return true until user provided invalid input . Read man 3 scanf and check return value.
Better run loop until you press key like Ctrl+d
for (; scanf("%d", &i) != EOF; printf("%d\n", i));
Or compare the return value of scanf(),as scanf("%d", &i) == 1 returns 1 as long as it is able to convert user input into integer.
for (; scanf("%d", &i) == 1; printf("%d\n", i));

That will run until scanf returns a zero value, so it could run forever so long as there's sufficient input. End-of-file will be zero.
This is a really ugly way of expressing that logic. Just use a while.
Actual files aren't infinite length, but there are things like the yes utility that produce endless streams of output that could be piped into a program like this.

Related

Can anyone explain me this output? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
#include <stdio.h>
int main(){
char arr[100];
printf("%d", scanf("%s", arr));
return 0;
}
Input value give for scanf is love2code
According to the C Standard (7.21.6.4 The scanf function)
3 The scanf function returns the value of the macro EOF if an input
failure occurs before the first conversion (if any) has completed.
Otherwise, the scanf function returns the number of input items
assigned, which can be fewer than provided for, or even zero, in the
event of an early matching failure.
So if the call of scanf was successful
scanf("%s", arr)
then its returned value is equal to 1 that is outputted by the call of printf.
printf("%d", scanf("%s", arr));
This statement can be rewritten like
int result = scanf("%s", arr);
printf("%d", result);
Pay attention to that the output does not depend on what string was entered (provided that ii can be accommodate in the array arr, otherwise there will be undefined behavior). It is important that only one item (arr) was assigned.

Is this program actually valid [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include<stdio.h>
int main()
{
char word[1000];
scanf("word%s", word);
printf("%s", word);
}
It seems that when I input any string, as long as I type out "word" first, I get proper output.
But is this program actually valid
It compiles and therefore is valid from a syntax perspective. It's also fine in order to check that a prefix is used.
However, there are at least two ways to get undefined behaviour:
scanf might store more than 1000 characters (read 999 and one for the final \0)
scanf might read none if the input does not start with "word"
You should therefore check the result of scanf, initialize word, and also limit the maximum number of characters that scanf reads:
#include<stdio.h>
int main()
{
char word[1000] = {0};
int ret = scanf("word%999s", word);
if ( ret == 1 ) {
printf("%s", word);
}
}
this program is valid ,but you have to be careful about buffer overflow , which means if user input more than 999 chars this will lead to undefined behavior , so I suggest this:
scanf("word%999s", word);
also as you said as long as I type out "word" first ,otherwise char word[1000] will be uninitialized.

How to read n numbers separated by space in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to read n integers from user during execution and the numbers are separated by spaces. It would be the best to be received as an array. For input 1 22 3 445 3, the result is, array[0]=1, array[1]=22 and so on. I have to do it in C. Can't use
scanf("%d %d %d", &var1, &var2, &var3);
because, I don't know how many such numbers would be inserted. The value of n would be read from user just before reading this data.
enum { MAX_NUMBERS = 1000000 }; // Choose appropriate upper bound
int n;
if (scanf("%d", &n) == 1 && n > 0 && n < MAX_NUMBERS)
{
int array[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &array[i]) != 1)
…process error — terminate loop?…
}
…use array…
}
You can read multiple numbers with scanf() using a loop as shown. You've no idea whether they were all presented on a single line, or each was on its own line, or whether there were many blank lines between successive numbers (or any permutation of all these possibilities).
The scanf() family of functions basically do not care about newlines — it is hard to force them to do so. When you care about line-based input, use fgets() or POSIX function getline() to read a line and sscanf() — or other string parsing functions — to process the line.
I'm assuming support for C99 with VLA (variable length arrays). The principles are the same without that support — the mechanics are a little different (and there are multiple options for how to do it).
Use fgets() and then strtok() with atoi().
Take the numbers as a string.
Here is one way to do it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char numbers[100];
int myn[100];
printf("Give me numbers..\n");
fgets(numbers,100,stdin);
const char s[2] = " ";
char *token;
token = strtok(numbers, s);
int i=0;
myn[i]=atoi(token);
while( token != NULL )
{
i++;
printf( " %s\n", token );
token = strtok(NULL, s);
myn[i]=atoi(token);
}
printf("You gave me: ");
for (int j=0; j<i; j++){
printf ("%d, ", myn[j]);
}
return(0);
}
The above C program does exactly what you want. At the for loop, it prints to the screen the numbers you gave from keyboard. The "problem" would be much easier by using enter instead of spaces between the numbers.
Click on the links, to see very useful details about the functions used.

c - how to break scanf with no enter and no string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project for school and in it, I need to get a four digit number and then continue immediately with no enter. For example: "Enter a number: 1424" and then it just continues, and you can't enter anymore numbers, aw well as Enter key pressing should not be needed.
I tried scanf("%4d",&num); but it waits for Enter key.
And one more restriction is... I can't use strings in this project, so all the solutions must be without strings.
The only way to organize input without Enter key press are functions getch and getche from conio.h header, that I suppose is not in C/C++ standard. So POSIX standard names are _getch and _getche.
With that functions you will read character - which are not strings if you process each char separately.
UPDATE:
My solution is:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch; // to store an input - single char
int number = 0; // to make number from inputs
printf("Enter a number: ");
int digits_cnt = 0;
while (digits_cnt < 4)
{
ch = _getche();
if (isdigit(ch))
{
number *= 10; // add an order to number
number += ch - '0'; // add a decimal digit to number
digits_cnt++; // count this digit to stop loop
}
}
// just to check result
printf("\nThe number %d was entered.\n", number);
return 0;
}
I assume that all 4 digits should become a number, but, perhaps, you need to do something else with them.
For reading 4 digits you probably want use char * fgets ( char * str, int num, FILE * stream ); that will do exactly what you are asking for. You should not use scanf for interactive input you can find why in this article
To the string part since you are typing input in ascii you are already working with strings(arrays of chars).

This program should output a number of primes, but when i input "total" it doesn't start.Where is the mistake? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
/* Program Print Prime Numbers */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int *primes=NULL;
int trial=0;
bool found=false;
size_t total=0;
size_t count=0;
printf("\nHow many primes would you like?\n");
scanf("%d",&total);
total=(total<4?4:total);
printf("%d",total);
primes= (int*)malloc(total*sizeof(int));
if(primes==NULL)
{
printf("\nNot enough memory\n");
return 1;
}
*primes=2;
*(primes+1)=3;
*(primes+2)=5;
count=3;
trial=5;
while(count<total);
{
trial+=2;
for(size_t i=0;i<count;i++)
if(!(found=(trial % *(primes+i))))
if(found)
*(primes+count++)=trial;
}
for(size_t i=0;i<total;i++)
{
if(!(i%5))
printf("\n");
printf("%d",*(primes+i));
}
printf("\n");
return 0;
}
This a C program from a book that i use to learn C Programming.
This program doesn't work.
When it should input the "total" variable, the program continue to input values.
How many primes would you like?
4
5
10...like this
... but when i input “total” it doesn't start.Where is the mistake?
Without commenting about the other problems, the reason that it doesn't start is that it goes into an infinite loop because you say:
while(count<total);
Remove the trailing ;.
scanf() is blocking call reading input from stdin until EOL is read. This means you have to start the program, type the desired number of primes and press enter, to end the input.
EDIT:
Some clarifications:
stdin is standart input. By default it's keyboard input.
EOL means end of line. It's a character marking end of line.
Blocking call means, that the program stops until the the call is finished. Functions for input are generally speaking blocking. Very simply put, the program is removed from processor, no instructions are executed, until the call is finished, unblocking the program.
The problem isn't with scanf() or enter as some suggested - this could be easily seen by fflushing the output after the first printf.
I found the source for your code, and you forgot a little important break which does all the difference:
while(count<total)
{
trial+=2;
for(size_t i=0;i<count;i++)
if(!(found=(trial % *(primes+i))))
break; // <-------------------- HERE.
if(found)
*(primes+count++)=trial;
}
Also, as suggested, there should be no trailing semicolon after the while clause-opening.
Just press "Enter" button to force your "scanf" to return its read value

Resources