(C) toothpick game has me stuck in a LOT of places - c

I've tried so many different things but cant organize the structure properly to get the game actually working
I have the shell and functions layered out, but cant properly implement my defined functions into the sections where they are needed.
#define ROUNDS 3
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void greeting();//display welcome message to user
int playRound(int round); //play one round
int humanPick(); //retrieve the user's guess
int computerPick(int choice, int leftover); //computer makes its pick
int leftOnTable(int toothpicks, int taken); //calculate number of toothpicks left
void winnerAnnouncment(int user); //overall winner of round announcement
int main()
{
void greeting();{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpics on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
}
for(int x = 0; x < ROUNDS; ++x)
{
int result = playRound(x + 1); //call playRound and assign result the value function returns
void winnerAnnouncement(int user){
if (user == )
}
}
printf("********************************************************\n");
printf("Thank you for playing!\n");
return 0;
}
int playRound(int round)
{
printf("Welcome to a new round %d!\n", round);
printf("You may go first!\n");
int toothpicks = 31; //number of toothpicks to start with
//int taken;
int leftOnTable(int toothpicks, int taken);{
int taken;
while(toothpicks > 0){
toothpicks = toothpicks - taken;
return toothpicks;
}
}
//loop that keeps track of toothpicks until respective no more toothpicks left.
while(toothpicks != 0)
{
printf("There are currently %d toothpicks left.\n", toothpicks);
printf("How many toothpicks are you going to take off the table?");
printf("Pick a number between 1 , 2 , and 3.\n");
scanf("%d", &userChoice);
int humanPick()
{
if (userChoice >= 1 && userChoice <= 3)
return userChoice;
if(userChoice < 1 || userChoice > 3)
return 0;
}
int computerPick(int choice, int leftover)
{
if (toothpicks > 4)
choice = 4 - leftover;
if (toothpicks = 2 || 3 || 4)
choice =
if (toothpicks = 1)
choice = toothpicks;
}
return toothpicks; //terminates loop
}
return 0;
}

You do not want to be defining functions inside of other functions. Although some compilers allow that as an extension, it is not part of the language. But, even if you are using a compiler that allows it, your syntax is wrong. Consider:
int leftOnTable(int toothpicks, int taken);{
int taken;
while(toothpicks > 0){
toothpicks = toothpicks - taken;
return toothpicks;
}
In the body of another function, the semi-colon after int taken) ends the declaration of the function, and the {...} after that is not a function definition but is just a block of commands to be executed in the enclosing function. You want to write this (outside of any enclosing function) as:
int
leftOnTable(int toothpicks, int taken)
{
...
}
and then call it as:
int
main(void)
{
...
int toothpicks = 31;
int taken = humanPick();
...
toothpicks = leftOnTable(toothpicks, taken);
...
}
Your attempt to define humanPick() seems incorrect. Getting user input is notoriously difficult, and scanf is almost always the wrong tool. (See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html). By "almost always", I am being conservative and I actually mean that it is absolutely never the right choice. But, if you want to use scanf, you might try something like:
int
humanPick(int toothpicks)
{
int userChoice;
printf("There are currently %d toothpicks left.\n", toothpicks);
puts("How many toothpicks are you going to take off the table?");
puts("Pick a number between 1, 2 and 3.");
int rv;
while( 1 != (rv = scanf("%6d", &userChoice))
|| userChoice > 3 || userChoice < 1 )
{
char *msg = "Invalid input.";
switch( rv ){
case EOF:
puts("Terminating. Thanks for playing!");
exit(0);
case 1:
msg = "Choice must be 1, 2, or 3";
/* Fall thru */
default:
fprintf(stderr, "%s. Try again\n", msg);
while( (rv = getchar()) != EOF && rv != '\n' ){
;
}
}
}
return userChoice;
}
Be aware that this function changes the function prototype, and this version take toothpicks as a parameter.
Note two things about the usage of scanf here that are absolutely essential. You must always check the value returned by scanf, and you must always use a width modifier on the conversion specifier in the format string. If you do not understand what this means, you should stop using scanf. Without a width modifier, the behavior is undefined for certain inputs. Note that using a width modifier on %d means that you cannot reliably scan the full range of values that can be stored in an integer, and this is just one more reason to avoid using scanf.

"but cant organize the structure properly"
This section will work the way you have it, but I would place the #define below the #includes:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define ROUNDS 3
Your prototype section looks okay, but its idiomatic in declarations to use (void) rather than ()
void greeting(void); //display welcome message to user
int playRound(int round); //play one round
int humanPick(void); //retrieve the user's guess
int computerPick(int choice, int leftover); //computer makes its pick
int leftOnTable(int toothpicks, int taken); //calculate number of toothpicks left
void winnerAnnouncment(int user); //overall winner of round announcement
The highest number of compile errors have to do with using nested functions. The C language does not support them, and it is not a good idea IMO to use extensions that allow them. The form of the program should be shaped like this:
int main(void)
{
// declare variables and call functions here
greeting();
//other constructs & function calls here.
return 0;
}
//Functions definitions should include 1 definition for each prototype:
void greeting(void)
{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpics on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
}
int playRound(int round)
{
//content here (but your current content has issues)
return something;
}
int humanPick(void)
{
//content here
return something;
}
int computerPick(int choice, int leftover)
{
//content here
return something;
}
...and so on.
Note also I see you are using = to do comparisons. = is an assignment operator, for example toothpicks = 2 means assign the value 2 to the variable toothpicks. If you want to check equality, then use ==, eg if(toothpicks == 2){do something}.
An additional general note about function implementation and usage. Functions are seen in different forms:
prototype - is a declaration in the code that instructs the compiler about the data type of the function, arguments and parameter list. example: int add(int a, int b);
definition - The signature of a function is presented in the same way as that of its prototype but includes {...} enclosures which contain the body of executable code the function is designed to execute during run-time. Example:
int add(int a, int b)
{
return a + b;
}
calling a function - When a function is called, its signature, including the decorations around its name are not shown, but instead contain objects that are of the same type as specified in the function formal signature. For example, inside main(), or some other function:
int sum = 0;
int a = 10;
int b = 20;
sub = add(a, b);
Keep in mind that syntax errors will always be flagged by a good compiler, and prevent an executable from being created. But the number and type of warning messages you see at compile time is settable, and depend to some extent on how you have your compiler set. Setting the warnings on your compiler to a strict enough setting will output messages to warn of syntax errors, or possible mis-use of operators, or regarding function definition / usage and often suggest how to correct. if using GCC for example set compiler to use -Wall.

Related

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.

My goal is to produce 2 functions that use while loops to:

a.) (function 1) take user input and decrement the value until userNum = zero
b.) (function 2) take the original user input and have zero increase by +1 until reaching said user input.
therefore, the output would look like this:
Please enter a positive integer: 5 (enters 5)
5
4
3
2
1
0
(four asterisks)
0
1
2
3
4
5
My problem is, I cant figure out how to set the original input for userNum in place so I can all it in the "loop_up_to_int" function. Any help would be appreciated, thank you.
#include <stdio.h>
int loop_down_to_zero(void);
int loop_up_to_int(void);
int main(int argc, char * argv[])
{
int userNum;
printf("Please enter a positive integer: ");
scanf("%d", &userNum);
//printf("%d\n", userNum);
loop_down_to_zero();
loop_up_to_int();
return 0;
}
//definitions here
int loop_down_to_zero() {
//scanf("%d", &userNum); do i scan for input here?
while (userNum >= 0) {
printf("%d\n", userNum);
userNum = userNum - 1;
}
printf("****\n");
}
int loop_up_to_int() {
int newNum;
int userNum;
newNum = 0;
printf("%d\n", newNum);
while (newNum != userNum)
{
newNum = newNum + 1;
printf("%d\n", newNum);
}
}
error message:
daily08.c:58:14: error: 'userNum' undeclared (first use in this function)
while (userNum >= 0) {
Your error message is because userNum doesn't exist in the function. It's only declared in main. Passing values is the solution.
You can pass values into functions (a core idea behind programming; variables shouldn't be global). Similar to how main has int in it's declaration; update both your functions to take a variable:
int loop_down_to_zero(int number)
Don't forget to update the function definition on top of your program also.
And you call the function by simply saying loop_down_to_zero(userNum). What you entered can now be accessed via number in each function, and userNum will stay intact in main().
Side note: When functions are done, they can return a value back to the caller. In your case you don't do that (nor do you need to). Both your functions should show they don't return anything, which is marked by using void i.e. void loop_down_to_zero(int number). Again remember to update the top of your program also.

Battleship game in C

I have been coding the battleship game in C but I have a few problems. First of all, I would like to have a counter for the "hit and sunk" ships (it is coded, but it doesn't seem to work, after you hit a ship, it always prints 1), and therefore, this doesn't end the program when all ships are sunk. Here is my code for the main and "shoot" functions:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define rows 5
#define columns 5
int mainint main(){
srand(time(NULL));
int grid[rows][columns], attemps=0, ships;
int sunk;
printf("Let's play the battleship game!\n");
printf("You have 20 tries.\n");
printf("Enter the number of ships: ");
scanf("%d",&ships);
prepare_grid(grid); //Prepare grid with items of value -1
gen_ships(grid,ships); //Generate random ships surrounded by water (value 1)
print_grid(grid); //Print grid without showing the generated ships (all items will be "~" meaning "undiscovered water).
sunk=0;
for (int a=0;a<20;a++){
shoot(grid,sunk,ships);
attemps++;
print_grid(grid);
printf("\nAttemps: %d\n",attemps);
}
print_secret_grid(grid); //Print final grid, showing all sunk ships and positions shot
return 0;
}
void shoot(int grid[rows][columns], int sunk, int ships) {
int x, y;
printf("\nLine --> ");
scanf("%d", &x);
printf("Column --> ");
scanf("%d", &y);
do {
if (grid[x-1][y-1] == 1) {
grid[x-1][y-1] = 2; //We assign value 2 because we want to print only the ones the user hits, it will print X which means "hit and sunk".
sunk++;
printf("\nHit and sunk\n");
printf("Sunk ships:%d \n\n", sunk);
} else if (grid[x - 1][y - 1] == -1) { //It will print "*" which means "discovered water".
grid[x - 1][y - 1] = 0;
printf("\nMiss\n\n");
}
}while (sunk=!ships);
}
When using a function call in C, the value is passed by copy. This means that
int value = 0;
function(value);
printf("%d\n", value);
will always print the value 0, even if the function reads like
void function(int value) {
value++;
}
because within the function function, a copy of the int value is being incremented.
To fix this, pass a copy of the memory location of value, and then increment the number stored at that location.
int value = 0;
function(&value);
with
void function(int* value) {
(*value)++;
}
sunk is passed by value. It needs to be passed by reference. Send the pointer to sunk, and receive sunk as a pointer in the shoot function.
Alternatively, make sunk a global variable and increment it, although I'd not suggest this for bigger programs!
Read more about passing by value and passing by reference to prevent such things from happening in the future! :D

Guess the number game, every # is low

I've been at this project for hours and hours trying to figure this out but I'm to the point of brain dead where everything I read leaves me confused.
The idea is to enter a number and the program will tell me whether it is right or wrong. Every single time, the end response after I enter a number is that the number is too low.
Also, the final answer states that the answer is too low and that it's correct at the same time.
Finally, this thing is suppose to ask again if the number entered is incorrect, yet I have no knowledge of how to do this.
Literally, the tiniest advice is much appreciated at this point. It's been a long, groaning night.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
//new function
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
//new function
int randomNumber(){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return 0;
}
//new function
int guessInput(){
int guess, range;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return 0;
}
//new function
int wrongAnswer(){
int guess, number;
if(guess < number)
{
printf("Try again, your guess is too low\n");
return 0;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit to high\n");
return 0;
}
return 0;
}
//new function
int correctAnswer(){
int guess, number;
if(guess == number)
printf("Great job! That time you got it right!\n");
return 0;
}
int main(){
welcomeMessage();
randomNumber();
guessInput();
wrongAnswer();
correctAnswer();
}
You're not actually passing the value of guess to wrongAnswer() or correctAnswer(). guess in those two functions is uninitialized and doesn't contain the value stored in guessInput(). This is why wrongAnswer tells you that the guess is too low and correctAnswer tells you that it's correct.
You'll also want to remove the number declaration within those functions. You have a global number right now that stores the random number, but the new number variable declared within your functions will take precedence -- it's uninitialized and doesn't contain the random number like you think it does.
You may want to adjust your wrongAnswer() and correctAnswer() functions to take guess as an integer argument, and remove the guess and number declarations within those two functions. Something like
int wrongAnswer(int guess);
int correctAnswer(int guess);
You may also want to consider having your guessInput() function return the value of guess. Try something like
int guessInput()
{
int guess;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return guess;
}
int main()
{
...
int guess = guessInput();
wrongAnswer(guess);
correctAnswer(guess);
...
}
This way you're passing the value of guess to your two functions so that they can actually evaluate whether the number is correct or incorrect.
You'll also want to look at the value of your return functions. Right now they aren't really telling you anything, and they return 0 regardless. Consider changing them to return 0 if the guess was correct and return 1 if the guess was incorrect.
int correctAnswer(int guess)
{
if(guess == number) {
printf("Great job! That time you got it right!\n");
return 0;
} else {
return 1;
}
}
With this information you can create a while loop to continually ask the user for input until they input the correct answer. Something like
int main()
{
...
int is_correct = 1, is_wrong = 1;
int guess;
while (is_correct == 1) {
guess = guess_input();
is_wrong = wrongAnswer(guess);
is_correct = correctAnswer(guess);
}
...
}
The while loop above will call each of the three functions, forever, until the user guesses the correct input. It evaluates is_correct == 1, constantly checking the value of is_correct, and repeating itself. When is_correct == 0 the loop will break and your program will terminate. This is where the return values I mentioned above come in -- a return value of 0 indicates a correct answer and will allow your program to stop. A return value of 1 will repeat the loop. There are other ways to do this, but it may help while you're starting out.
Hopefully this helps you out. I'd also consider redesigning your wrongAnswer() and correctAnswer() functions -- do you really need two? Could you reduce that to one function?
The Most basic issue that i see with the program is that you are not passing values to the functions. Each function is just working in itself and the value or should i say the 'number' it has to work with is not being passed into them.
You can use global variables or pass the values directly. This is what i would do:
The input function:
int guessInput(){
int guess, range;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return guess;}
The Random Number Generator Function:
int randomNumber(){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;}
The Answer Function: ( you really don't need 2 functions for this )
int Answer(int guess, int number){
int counter=0;
if(guess < number)
{
printf("Try again, your guess is too low\n");
counter=1;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit to high\n");
counter=1;
}
else if(guess == number)
{
printf("Great job! That time you got it right!\n");
counter=2;
}
return counter;}
Now that all your functions can accept variables, Modify the Main function
int main(){
int number=0;
int guess=0;
int answr=0; // This does not have to exist but since your doing a return.
welcomeMessage();
number=randomNumber();
guess=guessInput();
Do {
answr=Answer(guess,number);
}(while answr<2)
}
So when the counter reaches 2, which means that the answer is right, the while loop will stop when the correct answer is guessed by the user.
PS: You may need to polish my code a bit since im also in a brain dead mode atm. :D

C program to calc avg etc

i wrote this code in class today with the teacher helping me but I'm home now and need guidance, I'm not sure what i should do next to get it to compile atleast
the objective is to:
create a menu
enter a number(option A)
dispaly the average (option B)
display the highest and lowest number(option C and D)
display the total of all numbers entered(option E)
display the total amount of numbers entered(option F)
and quit(option G)
here is what i have so far, i apologies if its messy
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
//int getNumber (aNumber) {
// printf("Enter an integer between 0 and 1000.\n");
// scanf("%i", &aNumber);
// int result;
// }
char getMenuLetter();
int getNumber();
//declare variables
int aNumber = 0;
float avg = 0.0;
int high = -1;
int low = 1001;
int total = 0;
int count = 0;
char getChoice = 'x';
int main() {
//proptotype functions
do {
getChoice = getMenuLetter();
switch (getChoice)
case 'A':
aNumber = getNumber();
count++;
total += aNumber;
low = testLow(aNumber, low)
high = testHigh(aNumber, high);
break;
case 'B';
avg = (double) total/count; //display avg
printf("The average is %.2f", avg);
break;
case 'C':
high = getHigh();
printf("The highest value of all the numbers entered is %i.\n", high); //display highest number
break;
case 'D':
low = getLow;
printf("The lowest value of all the numbers entered is %i.\n", low); //displayer lowest value
break;
case 'E':
printf("The total of all the numbers entered is %i.\n", total);
break;
case 'F':
printf("The amount of numbers entered so far is %i.\n", count);
case 'G';
break: //end switch
} while (userChoice != 'G');
}
int testLow(int n) {
int result;
if (n < low)
result = n;
else
return 0;
} //End of main
char getMenuLetter() {
char result;
system("cls") //clear the screen.
printf("*************************************************\n");
printf("A) Enter a number between 0 and 1,000\n");
printf("B) Display the average\n");
printf("C) Display the highest value entered\n");
printf("D) Display the lowest value entered\n");
printf("E) Display the sum of all numbers\n");
printf("F) Display the count of all numbers entered\n");
printf("G) Quit the program\n");
printf("*************************************************\n");
scanf("%c", &result);
result =toupper(result);
///print f %c
//system pause
if (result != 'A' || result != 'B' || result !='C' || result !='D' || result !='E' || result != 'F' || result !='G'){
printf("You must enter A - G only! \n)");
system("pause");
} //end if
} while(result != 'A' || result != 'B' || result !='C' || result !='D' || result !='E' || result != 'F' || result !='G');
return result;
//end of GetMenuLetter
Here is what I suggest:
Compile your program first. Your compiler will return most of your errors (the important ones, at least).
Pay attention to your use of curly bases. In C (and in many other languages), the compiler will treat lines that follow other lines linearly. The curly braces cause a multidimensional interpretation. As a beginner to programming, you should practice using curly braces where you can, just so you get into the habit of segregating instructions. Also, you should pay close attention to matching your open curly braces with your closed curly braces. For more information, you should see the C Standard, 6.8: Statements and Blocks.
Your switch() block should end with a default: value, just in case you reach a choice that's unexpected.
I don't suggest putting your functions prototype inside your main() procedure. It has to do with scopes. Check this out, from Section 6.2.1 of the standard.
2 For each different entity that an identifier designates, the identifier
is visible (i.e., can be used) only within a region of program text
called its scope. Different entities designated by the same identifier
either have different scopes, or are in different name spaces. There
are four kinds of scopes: function, file, block, and function
prototype. (A function prototype is a declaration of a function that
declares the types of its parameters.)
I don't know what else to tell you. Try what I proposed in order. Make sure you read the standard though. As a final suggestion: try programming in a more ordered manner. Your code won't look so sloppy if you keep coding under the intent of wanting to make something you can read by the time you're finished.
Good luck.
Some hints:
Check your compiler errors and warnings beginning with the first.
Switch on additional warnings of your compiler (e.g. parameters -W -Wall for gcc).
There is a significant difference between ";" and ":" in C.
The body of a switch statement has to be enclosed in curly braces.

Resources