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.
Related
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.
I am a student and just 4 weeks into programming and I hope I can get help here huehue. So I am making a program where you can translate decimal numbers into octal and binary and vice versa. The program continues to ask the user to choose until they choose letter d to exit the program. The program seems to run fine at first but when I tried to use again the same letter and input values, the output seems to stack from the output from the last time, not overwriting I guess(sorry if my terminologies or grammar is wrong, I am not that good in english)What do I need to change? I can't figur it out huhuhu.
#include<stdio.h>
#include<math.h>
int main(){
int c, k, r=0, e=0, dec=0, o=0, place=1;
long n;
char choice, new, d;
do{
printf("Choices:\na. Decimal to binary and octal\nb. Octal to decimal and binary\nd. Exit.\n\n");
printf("enter your choice:\t");
printf("\n");
scanf(" %c", &choice);
switch(choice){
case 'A':
case 'a':
printf("Conversion: Decimal to binary and octal.\n");
printf("Enter number:\n");
scanf("%ld", &n);
printf("%ld is ", n);
for (c =28; c >= 0; c--){
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf(" in Binary Form. \n");
printf("%ld is ", n);
while (n != 0)
{
o=o+(n%8)*place;
n=n/8;
place=place*10;
}
printf("%ld in Octal Form.\n\n", o);
break;
case 'b':
case 'B':
printf("Conversion: Octal to decimal and binary.\n");
printf("Enter number:\n");
scanf("%ld", &n);
printf("%ld is ", n);
for (c =28; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf(" in Binary Form.\n", n, k);
printf("%ld is ", n);
while(n!=0)
{
r=n%10;
dec=dec+r*(pow (8, e));
n=n/10;
e++;
}
printf("%ld in Decimal Form.\n", dec);
default:
printf("Exit.\n\n");
break;
}
}while(choice == 'a'|| choice =='A'|| choice == 'b'|| choice =='B');
return 0;
}
If I run the program with choice 'a' and enter 12, it returns:
12 is 00000000000000000000000001100 in Binary Form.
12 is 14 in Octal Form.
and if I do it again:
12 is 00000000000000000000000001100 in Binary Form.
12 is 1414 in Octal Form.
This is what you should tell us that level of detail as part of the question.
The minimal(ish) fix is to move the variables you initialize into the loop:
int main() {
char choice;
do {
int c, k, r=0, e=0, dec=0, o=0, place=1;
long n;
char new, d;
...
I moved all the declarations even though only the ones that were initialized were required to be moved. This reduces the scope of variables which usually a good practice.
Here are some other suggestions:
Both your switch and the last while loop check for the same thing. If use a if-else if loop instead you can use break to exit the loop. The other option is set a done indicator variable and check that in the loop.
I would also normalize the choice variable, i.e. choice = tolower(choice) so you don't have to check both lower and upper cases.
Consider driving the i/o in the main loop, then call a function that returns data which the main loop then prints out.
Use functions to eliminate duplication (i.e. the binary algorithm should probably be a separate function).
The binary algorithm looks wrong, btw, why does it loop 29 times? You pass it a long which might be 64 bits (at least it is on my system).
You read (signed) long but don't deal with negative values. #WeatherVane.
Value you read, n, doesn't seem to be validated. Should be able to type 'a' for a decimal or octal value? Or 9 for an octal value? Related to that, scanf() can fail so check what it returns.
You say 'd' exits but program logic is anything but 'a' or 'b' (in lower or uppercase) exits.
Formatting matters to people reading your code, so fix the wrong indentation of for (c =28; c >= 0; c--){. I would also suggest you use tab (or 8 spaces). This will encourage you to minimize how many levels you indent your code.
I'm a C beginner, and this is by far my biggest program yet. It incorporates do while loops to restart the program, allow the user to add as many numbers as they want and ensure the correct letters are submitted for yes or no. Simple enough. Thing is, every number that I type adds up to 0.00, and the program gives me a segmentation fault (core dumped) error regardless of my choice for restart.
Errors:
I'm well aware that this could be some stupid detail I overlooked, but bear with me! Help is greatly appreciated.
Code:
/*Basic addition program*/
/*May 31 2018*/
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char restart;
//Loop for restart
do{
/*
Starts Variables for Current number, sum,
number place count, and restart choice
*/
float currnum, sum;
int count = 1;
char restart = 'N';
//Loop for user input amount until 0 is submitted
do{
//Initiates number place ending array
char end[3];
printf("Basic Addition Program\nType 0 To Terminate\n\n");
//Chooses which ending to add to array
if(count == 1){
strcpy(end, "st");
}else if(count == 2){
strcpy(end, "nd");
}else if(count == 3){
strcpy(end, "rd");
}else if(count > 3){
strcpy(end, "th");
}
//Requests user input and adds to current number float
printf("Enter %d%s number: ", count, end);
scanf(" %d", &currnum);
//Clears Screen (Unix)
system("clear");
//Adds current number to overall sum
sum += currnum;
//Increases number count so that places shift by 1 (e.g 1st to 2nd)
count++;
}while(currnum != 0);
//States numbers inputted and sum
printf("You added %d numbers and got a sum of %.2f\n", count, sum);
//Do while loop for user error
do{
printf("Restart?(Y/N): ");
scanf(" %c", restart);
//Tests if numbers have ben inputted in lowercase and corrects accordingly
if(restart == 'y'){
restart = 'Y';
}else if(restart == 'n'){
restart = 'N';
}
}while(restart != 'Y' || restart != 'N' );
}while(restart == 'Y');
return 0;
}
One of the problematic statement is
scanf(" %c", restart); /* you need to provide the &(address) to store */
It should be
scanf(" %c", &restart);
you should read the compiler warning & solve yourself & compile with -Wall flag.
Also below statement
scanf("%d", &currnum); /* currnum is declared as float variable, use %f */
In the below code block
char restart;
do {
/* some code */
}while(restart == 'Y');
the restart is not initialized, your compiler could have warn you like
error: ‘restart’ is used uninitialized in this function
[-Werror=uninitialized]
So at the very first initialize restart like
char restart = 'Y';
and finally if you want to learn C properly, treat all warnings as error & then start solving problems. for e.g compile like below
gcc -Wall -pedantic -Wstrict-prototypes -Werror test.c
I have made this program to calculate expressions like '2 + 6 - 9'(with spaces between numbers and operators), but the last if block is not correct. How can I break the loop when \n is received, and also store the input if not.
#include <stdio.h>
#include<stdlib.h>
void main()
{
char oper;
int sum,y;
scanf("%d %c",&sum,&oper);
while(1)
{
scanf("%d",&y);
if(oper=='+')
sum += y;
else if(oper=='-')
sum -= y;
else if(oper=='/')
sum /= y;
else if(oper=='*')
sum += y;
if((scanf("%c",&oper))=='\n')
break;
}
printf("\n =%d",sum);
}
See the documentation for scanf
On success, the function returns the number of items of the argument list successfully filled.
Replace this part:
if((scanf("%c",&oper))=='\n')
break;
with:
if(scanf("%c",&oper) && oper=='\n')
break;
This:
checks whether scanf() has put any value into oper
if yes then it checks if the value is equal to \n
Im currently writing a program which calculates the fibonacci number of a given integer using recursion. I created my own function 'fibonacci' and made the program to run on loops as you can see in the code.
The program wants me to use switch statement to operate the menu (The menu is the one where the user gets two options of either choosing to find fibonacci or to exit the program), and I am stuck on how to use switch statement in order to use the menu.
Here is the code I wrote so far
#include <stdio.h>
int fibonacci(int num);
int main(int argc, char const *argv[]) {
int choice;
int num;
int sequence;
printf("1) Calculate Fibonacci\n");
printf("2) Exit\n");
scanf("%d", &choice);
if (choice == 1)
{
do
{
printf("Input integer n :\n");
scanf("%d", &num);
if (num < 0)
{
printf("n should be a positive integer (n >= 1). Retry\n");
}
} while (num < 0);
}
if (choice == 1 && num > 0)
{
printf("Fibonacci sequence of %d terms\n", num);
From "The C Programming Language" by Kernighan and Ritchie:
"The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly."
So it should look similar to this:
while ((choice = getchar())!= EOF){
switch (choice){
case '1':
// calculate Fibonacci sequence
break;
case '2':
return 0;
}
}
As one of the comments suggests, either initialize your local variables in the beginning or check the return value of your getchar() or scanf() calls, since values of uninitialized variables are indeterminate.
If you've just started studying C, I suggest that you read the book that I mentioned. It's relatively short and has lots of helpful examples.