Using codeblocks writing a c program that repeatedly prompts for input - c

Key points, I'm using Codeblocks to write this program, and it needs to be written with the intent of writing C only and nothing more. I want it to be as basic as possible. So this is the mess that I have so far.
I need this program to continue to ask the user for a value until between 1-29 until it reaches 176. Once it exceeds 176 all I need to do is print the sum of the numbers, the largest number entered and the smallest number entered.
From there the program needs to loop and ask if another set of numbers will be entered. Terminating the program with the appropriate user input. I need to output the following info:
Sum of all numbers
Largest number entered
smallest number entered
If anyone has any advice that would help a lot.
/* Matthew Gambrell CSC 120 12/4/14*/
#include <stdio.h>
main ()
{
int total, num, large, small, again;
again=1;
while (again==1);
{
total = 0;
large = 0;
small = 50;
}
while(total<=176);
{
num=inputNum();
total=tot(num, total);
large=CheckLarge(num, total);
small=CheckSmall(num, small);}
printresult(total, large, small);
printf("play again");
printf("1=yes 0=no");
scanf("%d", &again);
}
float inputNum();
{
float badnum, num;
badnum=1;
while (badnum==1);
printf("please enter a number between 1 and 29");
scanf("%f", &num);
if(num>0 and num<30)
badnum = 0;
else
printf("error renter");
getch("press enter to continue");
return(num)
}
tot(num, total)
total += num
return (total)
}
return(num)

Like your classmate said, you can do this using a loop within a loop. The structure of your code makes it seem like this was your goal.
Firstly, as mentioned in the comments, remove your semicolons from the end of your while(..); statements. This will allow control to enter the blocks you're defining below them.
Secondly, you probably want to place the closing bracket for your first while loop after the end of your second while loop. This is your 'loop within a loop' structure.
Thirdly, you don't have any real way of displaying your results at present. Usually, your int main(){ ... } function returns a number relating to how your program went. Whilst you can have it return your total variable, it's more likely you want it to return 0;, and output your variables to screen during program execution.
For example, as you did in your input parsing in inputNum(..), you can write
printf('The total is %i\n', total);
printf('The largest number entered was %i\n', large);
printf('The smallest number entered was %i\n', small);
These numbers (large and small) will need to be within your (first) while loop - they should be reset each time your loop restarts, but not each time you enter a number.

Related

Couldn't get rid of multiple outputs in a C program

I couldn't share the original code but the below program is as similar to my problem.
#include<stdio.h>
#include<conio.h>
void clrscr(void);
int reverse_of(int t,int r)
{
int n=t;
r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n",n); /*displays the input*/
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
return r; /*returns the value to main function*/
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
};
int main()
{
int n,r;
void clrscr();
printf("Enter a number: ");
scanf("%d",&n);
//while (n!=0) /*Use this for any number of digits*/
/* {
int z=n%10;
r=r*10+z;
n=n/10;
} */
r=reverse_of(n,r);
printf("The reverse of your number is: %d\n",r);
return 0;
};
This program displays the reverse of a 4 digit number. it works perfect when my first input is a 4 digit number. The output is as below.
(Keep in mind that i dont want this program to display the reverse of
a number unless its 4 digit)
Enter a number: 1234
Your number is: 1234
The reverse of your number is: 4321
Now when i give a non 4 digit number as the first input the program displays that it is not a 4 digit number and asks me for a 4 digit number. Now when i give a 4 digit number as the second input. It returns the correct answer along with another answer which is supposed to be the answer for the first input. (since the program cannot find the reverse value of a non 4 digit number the output always return 0 in that particular case). If i give 5 wrong inputs it displays 5 extra answers. Help me get rid of this.
Below is the output when i give multiple wrong inputs.
Enter a number: 12
The number you entered is 2 digit so please enter a four digit number
Enter a number: 35
The number you entered is 2 digit so please enter a four digit number
Enter a number: 455
The number you entered is 3 digit so please enter a four digit number
Enter a number: 65555
The number you entered is 5 digit so please enter a four digit number
Enter a number: 2354
Your number is: 2354
The reverse of your number is: 4532
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
Help me remove these extra outputs btw im using visual studio code and mingw compiler.
The problem lies here:
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
You're calling main() from reverse_of().
Try replacing the main(); with return 0; and in main(), do this:
int n,r;
do{
printf("Enter a number: ");
scanf("%d",&n);
r=reverse_of(n,r);
}while(r==0);
printf("The reverse of your number is: %d\n",r);
This happens because of the multiple recursion caused by the call of main() inside of the reverse_of function.
To avoid such thing you can move the printf("The reverse of your number is: %d\n", r); to the inside of the if(count==4){} and your problem is solved!
Also, note that your reverse_of functions does not need to receive the int r, instead it can be written like this:
#include <stdio.h>
int reverse_of(int t)
{
int n = t;
int r = 0;
int count = 0;
while (t != 0) /*Loop to check the number of digits*/
{
count++;
t = t / 10;
}
if (count == 4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n", n); /*displays the input*/
while (n != 0) /*This loop will reverse the input*/
{
int z = n % 10;
r = r * 10 + z;
n = n / 10;
}
printf("The reverse of your number is: %d\n", r);
return 1;
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n", count);
return 0;
}
};
int main()
{
int n, r=0;
while (r!=1){
printf("Enter a number: ");
scanf("%d", &n);
r=reverse_of(n);
}
return 0;
};
Hope it helped!
Well, your program has some ambiguity: If you stop as soon as you get 0, then the reverse of 1300, 130 and 13 will be the same number, '31'.
So, first of all you need two parameters in your function, to deal with the number of digits you are considering, so you don't stop as soon as the input number is zero, but when all digits have been processed. Then you extract digits from the least significant, and add them to the result in the least significant place. This can be done with this routine:
int reverse_digits(int source, int digits, int base)
{
int i, result = 0;
for (i = 0; i < digits; i++) {
int dig = source % base; /* extract the digit from source */
source /= base; /* shift the source to the right one digit */
result *= base; /* shift the result to the left one digit */
result += dig; /* add the digit to the result on the right */
}
return result;
}
The extra parameter base will allow you to operate in any base you can represent the number. Voila!!!! :)
#include <stdio.h>
int main()
{
int src;
while (scanf("%d", &src) == 1) {
printf("%d => %d\n",
src,
reverse_digits(src, 5, 10));
}
}
will provide you a main() to test it.
In contrast to C++, in C, it is allowed to call main recursively. But it is still not recommended. There are only a few situations where it may be meaningful to do this. This is not one of them.
Recursion should only be used if you somehow limit the depth of the recursion, otherwise you risk a stack overflow. In this case, you would probably have to call the function main recursively several thousand times in order for it to become a problem, which would mean that the user would have to enter a value that is not 4 digits several thousand times, in order to make your program crash. Therefore, it is highly unlikely that this will ever become a problem. But it is still bad program design which may bite you some day. For example, if you ever change your program so that it doesn't take input from the user, but instead takes input from a file, and that file provides bad input several thousand times, then this may cause your program to crash.
Therefore, you should not use recursion to solve this problem.
The other answers have solved the problem in the following ways:
This answer solves the problem by making the function reverse_of not return the reversed value, but to instead directly print it to the screen, so that it does not have to be returned. Therefore, the return value of the function reverse_of can be used for the sole purpose of indicating to the calling function whether the function failed due to bad input or not, so that the calling function knows whether the input must be repeated. However, this solution may not be ideal, because normally, you probably want the individual functions to have a clear area of responsibility. To achieve this clear area of responsibility, you may want the function main to handle all the input and output and you may want the function reverse_of to do nothing else than calculate the reverse number (or indicate a failure if that is not possible). The fact that you defined your function reverse_of to return an int indicates that this may be what you originally intended your function to do.
This answer solves the problem by reserving a special return value (in this case 0) of the function reverse_of to indicate that the function failed due to bad input, so that the calling function knows that the input must be repeated. For all other values, the calling function knows that the function reverse_of succeeded. In this case, that solution works, because the value 0 cannot be returned on success, so the calling function can be sure that this value must indicate a failure. Therefore, in your particular case, this is a good solution. However, it is not very flexible, as it relies on the fact that a return value exists that unambiguously indicates a failure (i.e. a value that cannot be returned on success).
A more flexible solution, which keeps a clear area of responsibility among the two functions as stated above, would be for the function reverse_of to not always return a single value, but rather to return up to two values: It will return one value to indicate whether it was successful or not, and if it was successful, it will return a second value, which will be the result (i.e. the reversed value).
However, in C, stricly speaking, functions are only able to return a single value. However, it is possible for the caller to pass the function an additional variable by reference, by passing a pointer to a variable.
In your code, you are declaring your function like this:
int reverse_of(int t,int r)
However, since you are not using the argument r as a function argument, but rather as a normal variable, the declaration is effectively the following:
int reverse_of( int t )
If you change this declaration to
bool reverse_of( int t, int *result )
then the calling function will now receive two pieces of information from the function reverse_of:
The bool return value will indicate whether the function was successful or not.
If the function was successful, then *result will indicate the actual result of the function, i.e. the reversed number.
I believe that this solution is cleaner than trying to pack both pieces of information into one variable.
Note that you must #include <stdbool.h> to be able to use the data type bool.
If you apply this to your code, then your code will look like this:
#include <stdio.h>
#include <stdbool.h>
bool reverse_of( int t, int *result )
{
int n=t;
int r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
*result = r;
return true;
}
else /*This will execute when the input is not a 4 digit number */
{
return false;
}
};
int main()
{
int n, result;
for (;;) //infinite loop
{
//prompt user for input
printf( "Enter a number: " );
//attempt to read number from user
if ( scanf( "%d",&n ) != 1 )
{
printf( "Invalid input!\n" );
//discard remainder of line
while ( getchar() != '\n' )
;
continue;
}
printf( "Your input is: %d\n", n );
//attempt to reverse the digits
if ( reverse_of( n, &result) )
break;
printf( "Reversing digits failed due to wrong number digits!\n" );
}
printf("The reverse of your number is: %d\n", result );
return 0;
};
Although the code is now cleaner in the sense that the area of responsibility of the functions is now clearer, it does have one disadvantage: In your original code, the function reverse_of provided error messages such as:
The number you entered is 5 digit so please enter a four digit number
However, since the function main is now handling all input and output, and it is unaware of the total number of digits that the function reverse_of found, it can only print this less specific error message:
Reversing digits failed due to wrong number digits!
If you really want to provide the same error message in your code, which specifies the number of digits that the user entered, then you could change the behavior of the function reverse_of in such a way that on success, it continues to write the reversed number to the address of result, but on failure, it instead writes the number of digits that the user entered. That way, the function main will be able to specify that number in the error message it generates for the user.
However, this is getting a bit complicated, and I am not sure if it is worth it. Therefore, if you really want main to print the number of digits that the user entered, then you may prefer to not restrict input and output to the function main as I have done in my code, but to keep your code structure as it is.

my for loop is not working properly in my code it keeps stopping after 1st cycle?

#include<stdio.h>
int main()
{
int i,n;
int arr[10]={};
printf("\n print all the entered elements in array");
printf("\n enter the value of n");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
printf("\n element no %d",n);
scanf("%d",arr[i]);
}
printf("\n the reversed elements are");
for(i=n-1;i<=0;i--)
{
printf("\n the numbers are %d",arr[i]);
}
return 0;
}
hey there this is my c program code and i have first enter the no of elemnts as how many element i want in that array and the have to print it in reverse order and i am facing some problem with this as when my first loop starts after 1 complete cycle or after taking one input on element i=0 it stops. i dont have any idea whats going on here so pls help me..
You want the address of the array element, not its value.
So, change
scanf("%d",arr[i]);
to
scanf("%d",&arr[i]);
(And, for your own sake, learn to not ignore the return value of scanf().)
Also, if you enter N as number of elements, then your code will need N+1 numbers entered, hoping that N+1 is less than 10.
This is because for(i=0;i<=n;i++) will need numbers entered for 0,1,2, ...N, because of the <=, you probably want <. You will then be asked one number less, which should fix the problem you describe. I.e. you should then see the "the reversed elements are" output after entering N elements. Your program currently seems to "stop" because it waits for another number being entered.
When you fixed that the next problem you encounter will be the one described in the comment by Tom Karzes. It prevents the output of "the numbers are".
Your continuation test is backwards. You want i >= 0, not i <= 0, since i is counting down to zero.
This means that, with your code as is, the body of the second loop will never be executed because with any meaningful n value, i<=0 for i==n-1 will already be false for the first check and the loop is immediatly done.

Assigning changing numbers to a single variable

Just screwing around in C... wanted to make a program that calculated the average of whatever numbers the user input.
The program works fine, I just can't 'logic' out how to do the next part.
I need to be able to take each number they input and average them, using the number they input for the first scanf to divide by. I only assigned one variable for each number they input, but after about a second of looking at the code I realized I would need to use calculus or some programming trick to be able to do this (effectively) infinitely. Basically, the variable needs to change each time so the sum can be taken then divided over the total number of numbers. I'm ranting...
Can anyone who can understand my stupid problem give me some pointers? That'd be great...
My includes and the int main () are there, don't worry. Just felt no need to clutter it with already known stuff. Also, I don't do shorthand anything- I feel no need to as of now.
// Base variables
int iUserReq, iNumCounter = 0;
// Each individual number
double dUserNum = 0.0;
// Calculation
double dNumSum = 0.0, dNumAvg = 0.0;
// Ask user for the number of variables to be averaged... will come in handy
printf("Please input how many numbers you would like to average together, as a number. For example, 10.\nTry to keep it low, because you're going to be putting them all in manually. > ");
scanf("%d", &iUserReq);
// If user inputs 0 or negative number, keep asking until they put in a positive number
while(iUserReq <= 0)
{
printf("Please input a number greater than 0. > ");
scanf("%d", &iUserReq);
}
// This adds a counter, so for the number of numbers the user wants to average, it will loop that many times and ask for an input that many times
// I.e. they want to average 10 numbers, it asks for 10 numbers
// THIS IS WHERE I'M STUCK... HELP?
while(iNumCounter < iUserReq)
{
printf("Please input number. > ");
scanf("%lf", &dUserNum);
iNumCounter = iNumCounter + 1;
}
return 0;
Thanks...
Bagger
OK, I'm going to bite and give you the solution.
At the top of your program:
double sum = 0.0;
After you scanf() for each number:
sum += dUserNum;
Just before return 0:
printf("%f\n", sum / iUserReq);
Do you understand why this works?

(C) Allow infinite of numbers to be entered, reverse the order of entered numbers & end program when 0 is entered

I'm working on a project at the moment where I have to allow a user to enter an infinite amount of numbers and reverse the order of those entered numbers and end the program if 0 is entered. I did something similar, except the one I did set the amount of numbers the user could enter, so for example in the code below, I allowed the user to enter only three numbers, reverse the order and end when -1 is entered.
#include <stdio.h>
#define MAX 3 // Defining max amount of numbers to be entered to 3
main()
{
int numbers[MAX], i, end;
printf ("Please enter %d integers:\n", MAX);
for (i = 0; i < MAX; i++){
scanf("%d", &numbers[i]);
if (numbers[i]==-1){ // Loop ends when -1 is entered
for (end=i; end<MAX; end++)
numbers[end]='\0'; // Nulls the value of blank locations in the array
i=MAX;
}
}
printf ("\nThe values in reverse order are:\n");
for (i = MAX-1; i >= 0; i--)
{
if(numbers[i]!='\0') // Will not print null values in the array
printf("\n%d ", numbers[i]);
}
return 0;
}
How can I go about achieving this? I'm guessing I won't be able to use an array, and I'm pretty new to this so...
No, arrays can't be grown dynamically (not without some extra tinkering, see comment below) so they can't hold an infinite amount of items.
You'll need some structure you can grow, C doesn't provide one so you'll have to use a third party implementation or write your own. A stack fits your problem the best.
Also, your loop will have to go on until -1 is entered. Either an infinite loop with a break statement, or a do-while loop that checks the entered number.
EDIT: The original question targeted C++, my original answer, below, is no longer relevant.
You want to look into C++'s STL. std::vector, std::deque or std::stack for example, would be useful in your case.
You can use a std::vector to do this.
Here's the declaration of your std::vector. Where the tells the vector you want it to be a vector of type int
std::vector<int> numbers;
Then to add to the end of the std::vector you use push_back(), which puts the integer onto the back of the array. The size of the vector will dynamically increase as you push more elements on to the back.
int input;
numbers.push_back(input);
Then to iterator through it you can use a reverse iterator or just iterate the same way you have been doing it using numbers.size() to find out how many elements are in the vector.

Sucessive integers using C programming

Example input: 20 10 5 20 2 20 20 20 2 2 0
Output:
(20*5)
(10*1)
(5*1)
(2*3)
I just started programming this semester and need help on a project. I apologize if my question is unclear.
So basically I have to input positive integers till I enter "0" would end the program. I'm not allowed to use arrays(whatever that means).
#include <stdio.h>
int main ()
{
int number, count=0
while(1)
{
scanf("%d",&number);
if (number!=0)
{
count++; continue;
}
else
{
printf("%d*%d",number,count);
break;
}
return 0;
}
How do I store these multiple numbers so that I wouldn't overlap the previous number and to increment duplicate numbers by 1 every time it's entered? I can't ask my professor for help; he just tells me to google it.
"A certain engineering apparatus is controlled by the input of successive numbers (integers).
If there is a run of the same number, the apparatus can optimize its performance. Hence we
would like to arrange the data so as to indicate that a run is coming. Write a C program that
reads a sequence of numbers and prints out each run of numbers in the form (n∗m) where
m is the number repeated n times. Note that a run can consist of just a single number. The
input numbers are terminated by a zero, which halts the apparatus."
This assignment seems to be based on half-baked knowledge of run length encoding (RLE). Anyway, here's a pseudo-code which does what it asks.
in = read next number from input
current_num = in // let the 1st number in list be current_num
count = 1
loop
in = read next number from input
if (in == 0) break // we are done, get out of loop
else if (in == current_num) count += 1
else // run has ended, print it and start new run
print current_num * count
current = in
count = 1
end loop
print current_num * count // we exited the loop before printing the last run
// so do it outside the loop
You can implement it in code and then "optimize" it to remove repeated code, and take care of corner cases (such as "empty" input, single number input, etc.)
Edit Just to be clear, the assignment asks for a 'run' of numbers, but the sample output shows a 'count' of numbers. These two are not the same.

Resources