Count till certain number with recursion with C language - c

i've been trying to do a program that counts till the number that the user inputs (f,ex: 10) with recursion.
If the user inputs 10, the program will have to print out: 1,2,3,4,5,6,7,8,9,10.
I'm getting a [1] 49348 segmentation fault ./recs.exe and i wanted to know why am i getting it to prevent it in the future.
Here is my code:
#include <stdio.h>
int numbers(int n);
int main(int argc, char const *argv[]) {
int number;
int i;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
for(i=0;i<=number;i++){
printf("%d, ", numbers(i));
}
}
int numbers(int n){
if(n==0||n==1){
return n;
} else {
return(numbers(n+1)); // I think the problem is here.
}
}
Hope you guys can explain my error and help me understand why it's happening to me to help me avoid this silly mistake. Thanks :)

You have a few issues in your algorithm.
the for loop calls the numbers program multiple times, starting the recursion multiple times. You need to start it only once, right?
you calling recursion with n+1, actually making every next invocation with an incremental value, which could be incremented indefinitely. Your recursion has no exit and will die with some out of memory or a crash.
To solve the first issue, just instantiate it once.
To print it correctly, you need to have the print statement withing the recursion.
For the second issue, you can do different approaches. The following is the easiest to understand and it passes max as a second argument.
void numbers(int n, int max) {
printf(%d ", n);
if (n >= max)
return;
numbers (n + 1, max);
}
int main() {
...
numbers(1, number);
}
a more efficient way is having a single argument and count it down to 0. But you have to be careful on when you want to print. In your case, if you need increment order of values, you have to make sure that the print happens after you return from recursion.
Here is the program which implements the second method:
#include <stdio.h>
void numbers(int n);
int main(int argc, char const *argv[]) {
int number;
int i;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
// start recursion.
numbers(number);
printf("\n");
}
void numbers(int n){
if (n == 0)
return;
numbers(n-1);
// after return from recursion
printf("%d ", n);
}

Your recursion never end if you send a number >= 2, for exemple, if i send 2 to your numbers function, the next call step is 3, the next one is 4, 5, 6 ect....
The correct code is :
int main(int argc, char const *argv[]) {
int number;
int i;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
for(i=0;i<=number;i++){
printf("%d, ", i);
}
if you want to do recursion, you can do a countdown, that lends more to the recursion
int main(int argc, char const *argv[]) {
int number;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
numbers(number);
}
void numbers(int n)
{
printf("%d, ", n);
if (n > 0)
numbers(n - 1);
}

As discussed in the comments, your implementation will not stop counting because it has no idea what the target value is. For example, if the user enters '2', the code would run numbers(0), which would return 0, then numbers(1) which would return 1, then numbers(2) which would call numbers(3) and so on, until the stack ran out of space.
The following should work according to my understanding of the problem.
void count(int from, int to)
{
printf( "%d", from );
if( from < to )
{
printf( ", ");
count( from+1, to );
}
}
int main(int argc, char const *argv[])
{
int number;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
count(1,number);
}
I've moved the printing into the recursive function because it makes it easier to output each number (and intelligently print the comma that comes between numbers), and it didn't make sense to me to use a recursive function and a for loop to count.
The function simply prints out the current value and then checks to see if it has reached its goal. If not, it recursively counts to the next number.

Related

taking the avg in C program

#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.

Some problems in coding a "guessing random number in C" under some conditions such as using input(), output()

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.

Write a program that multiplies user entered number till product of these numbers reach 1000

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;
}

Lottery Program Problems

I'm currently in progress of creating my second main C program. I've only just started to learn C and I've had a few problems, as well confusion on what to do next with this program.
The idea is to basically allow the user to enter in a desired amount of years, then the program simulates the lottery games played every week, depending on how many years they enter. Then inside the program, I want the two arrays to compare to each other and check for any numbers they both have at the same time. The lottery ticket on the user's end stays the same, which is set inside the array and of course, the random lottery numbers change every week.
The basics are done, I'm just having a few problems, as well as not knowing where to go in certain areas.
Problems:
"int weeks = year * 52" doesn't work, says the initializer element isn't constant.
When I return the get_lotto_draw, I just get a bunched up number, it's not seperated in anyway, so I'm not sure how to do that.
#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations
//Declaring Variables
int year;
char name[15];
char option;
int lotteryPlayer[] = {5,11,15,33,42,43};
int i;
int randomNums[49];
int *lotteryPtr = lotteryPlayer;
int *randomPtr = randomNums;
int weeks = 0;
void print_array(int *lotteryPtr);
int* get_lotto_draw(int *randomPtr);
//Main Method
int main(int argc, char *argv[])
{
start: //Start of program
printf("\n---------------------------");
printf("\nProject: Jackpot Dreams ");
printf("\n---------------------------\n");
printf("\nWhat is your First Name?:> "); //Asks them for their choice
scanf("%s", &name); //Reads the input
printf("\nHow Many Years to Sleep?:> "); //Asks them for their choice
scanf("%d", &year); //Reads the input
weeks = year * 52;
printf("\nOk %s, I will play the lottery for %d years!\n",name, year);
sleep(1500);
printf("Sweet Dreams %s, don't let the bed bugs bite", &name);
sleep(1500);
printf(". ");
sleep(1500);
printf(". ");
sleep(1500);
printf(".");
sleep(2000);
printf("%d", get_lotto_draw);
system("PAUSE");
}
//Returns an array of six random lottery numbers 1-49
int* get_lotto_draw(int *randomPtr)
{
for (i=0 ; i<weeks ; i++)
return randomNums;
}
//Print out the content of an array
void print_array(int *lotteryPtr)
{
printf("Hello");
}
//Returns number of matches between two arrays
int find_matches(int * lotteryPtr, int * randomPtr)
{
}
Update:
#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations
//Declaring Variables
int year;
char name[15];
char option;
int lotteryPlayer[] = {5,11,15,33,42,43};
int i;
int randomNums[49];
int *lotteryPtr = lotteryPlayer;
int *randomPtr = randomNums;
int weeks = 0;
void print_array(int *lotteryPtr);
int* get_lotto_draw(int *randomPtr);
//Main Method
int main(int argc, char *argv[])
{
start: //Start of program
printf("\n---------------------------");
printf("\nProject: Jackpot Dreams ");
printf("\n---------------------------\n");
printf("\nWhat is your First Name?:> "); //Asks them for their choice
scanf("%s", name); //Reads the input
printf("\nHow Many Years to Sleep?:> "); //Asks them for their choice
scanf("%d", &year); //Reads the input
weeks = year * 52;
printf("\nOk %s, I will play the lottery for %d years!\n",name, year);
sleep(1500);
printf("Sweet Dreams %s, don't let the bed bugs bite", &name);
sleep(1500);
printf(". ");
sleep(1500);
printf(". ");
sleep(1500);
printf(".");
sleep(2000);
printf("%d", get_lotto_draw(*randomPtr));
system("PAUSE");
}
//Returns an array of six random lottery numbers 1-49
int* get_lotto_draw(int *randomPtr)
{
for (i=0 ; i<weeks ; i++)
return randomNums;
}
//Print out the content of an array
void print_array(int *lotteryPtr)
{
printf("Hello");
}
//Returns number of matches between two arrays
int find_matches(int * lotteryPtr, int * randomPtr)
{
}
Borrowing mostly from the comments, there are a few problems with your code.
int weeks = year * 52; results in an error because year hasn't been initialized. Change it to int weeks = 0;, and then put weeks = year * 52 at the beginning of your main function.
You don't need the start: label at the beginning of your program, unless for some reason you want to go back there using a goto, which is usually considered bad practice.
printf("%d", get_lotto_draw); prints the address of get_lotto_draw as a decimal ("%d"), you need to make it get_lotto_draw(args) to get the return value of get_lotto_draw.
system("PAUSE"), runs the command PAUSE on the shell. I don't know if this will pause the current program, but if you don't want the program to exit, a loop will do instead.
while (1) {}
Your implementation of get_lotto_draw doesn't do what you think it does. What you are doing now is just returning randomNums, what you want to do is generate a random number between 1 and 49. To do this you should first generate a random number, and mod it by 48 and add one. This will get you a random number between 1 and 49. srand(time(NULL)); int r = rand(); will generate a random number, and r %= 48; r += 1; will mod it by 48 and add one. You can then do this for each iteration of that for loop, and create an array with the values. The array that you will return will have to be malloc'd.
int get_lotto_draw() {
srand(time(NULL));
int* rv = malloc(sizeof(int) * 6);
for (int i = 0; i < 6; i++) {
rv[i] = (rand() % 48) + 1;
}
return rv;
}
Your find_matches function is also unimplemented. Simply iterating through the arrays to find matches should suffice.
int find_matches(int* a, int* b) {
int matches = 0;
for (int i = 0; i < 6; i++) {
if (a[i] == b[i]) {
matches++;
}
}
return matches;
}
Lastly, for your print_array function, you again just need to iterate through the list of lottery numbers, and print each one.
void print_array(int* arr) {
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("%d", arr[5]);
printf("\n"); // remove this if you don't want a newline at the end.
}

Getting program to repeat over input in C

Hi I'm just starting programming in C and am struggling to write a program designed to take a string of integers and then output if the value being checked is smaller than the one before it. But I cannot get the program to repeat over the data and it seems to only be checking the first value. I have tried using loops but this further confused me. Sorry to ask such a basic question. Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
int num;
int smaller=0;
printf("Input integers: ");
scanf("%d", &num);
if (num<smaller) {
printf("*** value %d is smaller than %d \n", num, smaller);
}
smaller=num;
return 0;
}
You could use a do-while loop to ask the user for values over and over again until they type something invalid, like 0:
int smaller=0;
int num=0;
do {
printf("Input an integer (0 to stop): ");
scanf("%d", &num);
if (num<smaller) {
printf("*** value %d is smaller than %d \n", num, smaller);
}
smaller=num;
} while (num != 0);

Resources