I've recently faced a programming problem, and it seems to me that the most optimized way of solving it is by using goto, even though it's not a good practice. The problem is: tell the user to enter a positive natural number ( > 0) and read the input. If this number is valid, tell the user the square of that number. Do this while the input is correct. I came up with a few solutions, but all of them seem to have problems. Here are two of them:
Solution 1 - Problem: Uses goto
#include <stdio.h>
int main()
{
int num;
_LOOP:
printf("Enter a positive natural number: ");
scanf("%i", &num);
if (num > 0) {
printf("Square: %i\n", num * num);
goto _LOOP;
}
printf("Invalid number\n");
return 0;
}
Solution 2 - Problem: Double-checks if num > 0 (code repetition)
#include <stdio.h>
int main()
{
int num;
do {
printf("Enter a positive natural number: ");
scanf("%i", &num);
if (num > 0)
printf("Square: %i\n", num * num);
} while (num > 0);
printf("Invalid number\n");
return 0;
}
Obviously, there are more ways to solve the problem, but all the other ones I came up with that do not use goto encouter the same code repetition problem. So, is there a solution where both goto and code repetitions are avoided? If not, which one should I go for?
Here's half the answer; try to fill in what's missing. Remember that sometimes it's better to structure your loop as "do something until..." rather than "do something while..."
for (;;) {
printf("Enter a positive natural number: ");
scanf("%i", &num);
if (num <= 0)
break;
printf("Square: %i\n", num * num);
}
printf("Invalid number\n");
[updated with #rdbo's answer]
What about breaking out of the loop? This is basically a goto statement to the end of the loop without explicitly using goto.
#include <stdio.h>
int main()
{
int num;
while(1) {
printf("Enter a positive natural number: ");
scanf("%i", &num);
if (num > 0) {
printf("Square: %i\n", num * num);
} else {
printf("Invalid number\n");
break;
}
}
return 0;
}
The other option: check a bool that stores if the continue condition is met. It reads much easier than the infinite loop/break approaches (to me) and there's no code repetition.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int num;
bool bContinue;
do {
printf("Enter a positive natural number: ");
scanf("%i", &num);
if (num > 0){
printf("Square: %i\n", num * num);
bContinue = true;
}
else{
printf("Invalid number\n");
bContinue = false;
}
} while (bContinue);
return 0;
}
For starters if you expect a non-negative number then the variable num should have an unsigned integer type for example unsigned int.
As it is written in your question the user can enter an invalid data or interrupt the input. You have to process such a situation.
Also the multiplication num * num can result in an overflow.
And using goto instead of a loop is indeed a bad idea.
Pay attention to that you should declare variables in minimum scopes where they are used.
To use the for loop for such a task is also a bad idea. It is much expressive to use a while loop.
The program can look the following way
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
while ( true )
{
printf( "Enter a positive natural number: " );
unsigned int num;
if ( scanf( "%u", &num ) != 1 || num == 0 ) break;
printf( "Square: %llu\n", ( unsigned long long )num * num );
}
puts( "Invalid number" );
return 0;
}
The program output might look like
Enter a positive natural number: 100000000
Square: 10000000000000000
Enter a positive natural number: 0
Invalid number
Or it would be even better to move the last output statement inside the while statement. Fo rexample
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
while ( true )
{
printf( "Enter a positive natural number: " );
unsigned int num;
if ( scanf( "%u", &num ) != 1 || num == 0 )
{
puts( "Invalid number" );
break;
}
printf( "Square: %llu\n", ( unsigned long long )num * num );
}
return 0;
}
I am a bit surprised nobody suggested functional decomposition yet.
Instead of writing a big pile of primitive statements, cut main up into smaller functions.
Apart from readability/maintainability benefits, it also helps eliminate code duplication in a very natural way.
In OP's case, getting input from the end user is a separate responsibility, and makes a good choice for a separate function.
static bool user_enters_number(int *ptr_to_num)
{
printf("Enter a positive natural number: ");
return scanf("%i", ptr_to_num) == 1;
}
Notice user_enters_number explicitly tests the return value of scanf.
This improve end-of-file handling.
Likewise, you could give number validation its own function.
This may seem like overkill (it's just num > 0, right?), but it gives us the opportunity to combine the validation with the resulting error message.
Printing "Invalid number" at the end of main feels wrong. Invalid numbers are not the only exit condition; end-of-file is another.
So instead, I will let the validation function determine the message.
As a bonus, this makes it possible to support multiple error types (e.g. separate messages for negative numbers and for zero).
static bool is_valid_number(int num)
{
bool ok = (num > 0);
if (!ok) printf("Invalid number\n");
return ok;
}
We now have two boolean-typed functions that can be neatly chained together with && and put inside the condition part of a loop, which is an idiomatic way of saying: if either one of these functions fails (i.e. returns false), immediately exit the loop.
What's left, is a very clean main function.
int main(void)
{
int num;
while (user_enters_number(&num) && is_valid_number(num))
{
printf("Square: %i\n", num * num);
}
}
To appreciate the benefits in terms of maintainability, try rewriting this code so that it accepts two numbers and prints their product.
int main(void)
{
int num1, num2;
while (user_enters_number(&num1) && is_valid_number(num1) &&
user_enters_number(&num2) && is_valid_number(num2))
{
printf("Product: %i\n", num1 * num2);
}
}
The changes are trivial, and limited to a single function
(though you might consider adding a parameter input_prompt to user_enters_number).
There is no performance penalty for this 'divide-and-conquer' approach: a smart compiler will do whatever is necessary to optimize the code, e.g. inline the functions.
Related
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.
I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.
Is there a better way to write the following code by eliminating the repeated condition in the if statement in C?
while (n < 0) {
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Error: please enter a positive integer\n");
}
}
Thank you.
Simply rework your loop breaking when correct input is given. This way the check is done only one time:
while (1)
{
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n >= 0)
break;
printf("Error: please enter a positive integer\n");
}
And, as specified in comments, an optimized compiler should be able to reverse the loop by itself.
This is something that IMO is best accomplished with a bit of refactoring:
#include <stdio.h>
#include <stdbool.h>
static bool get_postive_integer(int *pOut) {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
if(n < 0)
return false;
*pOut = n;
return true;
}
int main(void)
{
int n;
while (!get_postive_integer(&n)) {
printf("Error: please enter a positive integer\n");
}
}
Give the operation a name, check that it fails, and only then print a message accordingly. The success or failure condition is only coded once here, in the named operation.
You could use:
while (printf("Enter a positive integer: ") > 0 &&
scanf("%d", &n) == 1 &&
n < 0)
{
printf("Error: please enter a positive integer\n");
}
This stops if the printf() fails, if the scanf() fails, or if the value in n is non-negative. It's a good idea to always check that the scanf() succeeds. It is merely convenient that printf() returns the number of characters it wrote (or a negative number on failure) so it can be used in a condition too. You could add fflush(stdout) == 0 && into the stack of operations too.
Or you could decide that the code in the condition should be in a function:
static int read_positive_integer(void)
{
int value;
if (printf("Enter a positive integer: ") > 0 &&
fflush(stdout) == 0 &&
scanf("%d", &value) == 1 &&
value >= 0)
return value;
return -1;
}
and then the calling code is:
while ((n = read_positive_integer()) < 0)
printf("Error: please enter a positive integer\n");
There are many variations on the theme; you might wrap the while loop into a function; you might make the prompts into parameters to the function. You might decide to be more careful about reporting what goes wrong (different actions if printf() fails compared with what happens if scanf() returns 0 (non-numeric data in the input) or EOF (no more data in the input).
The following examples are presented in the spirit that people should know what is available in the language.1 The way I would usually write the code is shown in Frankie_C’s answer. As some have noted, optimization usually makes this simple case not worth worrying about, but the question is not limited to a simple evaluation like n < 0; the test might be a function call to some expensive evaluation of more complicated criteria.
Folks are not going to like this, but:
goto middle;
do
{
printf("Error, please enter a positive integer\n");
middle:
printf("Enter a positive integer: ");
scanf("%d", &n);
} while (n < 0);
If you are vehemently opposed to goto, you can use a stripped-down version of Duff’s device:
switch (0)
do
{
printf("Error, please enter a positive integer\n");
case 0:
printf("Enter a positive integer: ");
scanf("%d", &n);
} while (n < 0);
But you should not.
Footnote
1 Commonly, software engineers will have to work with code written by others, so they must be prepared to recognize and understand anything expressible in the language, even if that is just a first step toward rewriting it into better code. And occasionally situations arise where “ugly” code becomes desirable for commercial or other practical reasons.
Another alternative is to split into a function:
int func(){
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
return scanf("%d", &n) == 1 ? n : -1;
}
and the loop becomes
while ((n = func()) < 0){
printf("Error: please enter a positive integer\n");
}
although the assignment in the condition check is not to everyone's taste. Note that I return -1 if the return value of scanf is not 1, something that you should always check.
What I do though in this situation (See Eric's answer) is to write
switch (0) do {
printf("Error, please enter a positive integer\n");
case 0:
printf("Enter a positive integer: ");
scanf("%d", &n);
} while (n/*ToDo - make sure n is initialised if scanf fails*/ < 0);
I'm trying to make an algorithm in C that asks you to input any number, and stops asking when you input the number 0. I'm supposed to do it with a while loop, but it doesn't work and I tried everything I've learned. This is my code that doesn't work:
#include<stdio.h>
int main()
{
int number;
while(number != 0)
{
printf("Introduce a number: ");
scanf("%i",&number);
}
return 0;
}
Hopefully it's not too late to bring my two cents to the party.
The solution which others suggest is definitely possible and working solution, however, I think it can be done in a slightly neater way. For cases like this, do while statement exists:
#include <stdio.h>
int main() {
int number; // Doesn't need to be initialized in this case
do {
printf("Introduce a number: ");
if (scanf("%i", &number) != 1) { // If the value couldn't be read, end the loop
number = 0;
}
} while (number != 0);
return 0;
}
The reason I think this solution is better is just that it doesn't bring any other magic constants to the code, hence it should be better readable.
If someone saw int number = 42;, for example, he'd be asking - Why 42? Why is the initial value 42? Is this value used somewhere? The answer is: No, it is not, thus it's not necessary to have it there.
You need to assign a number to number before using it in the condition.
You have two options: a) use a dummy initial value, or b) scanf before test
// a) dummy value
int number = 42;
while (number != 0) { /* ... */ }
or
// b) scanf before test
int number; // uninitialized
do {
if(scanf("%i", &number) != 1) exit(EXIT_FAILURE);
} while (number != 0);
int number = 1;
while(number != 0){
printf("Introduce a number: ");
scanf("%i",&number);
}
Scanf will pause loop and waiting for typing a number
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}