For example if i enter: "123456-7". The output at the first print statement would be: "123456-7" and at the 2nd print statement it would be "7". Which is correct.
But at any point after the break if I print the array again the print statement would go wrong in the last digit. It would look like: "123456-1" and the second would look like "1".
#include <stdio.h>
int main()
{
int lotoNumbers[6];
int ticketNumbers[6];
char option;
while(option != 'C')
{
printf("Your option:");
scanf(" %c", &option);
switch(option)
{
case 'W': printf("Please enter todays winning ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &lotoNumbers[0], &lotoNumbers[1], &lotoNumbers[2], &lotoNumbers[3], &lotoNumbers[4], &lotoNumbers[5], &lotoNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("----The following numbers matched! %d\n", lotoNumbers[6]);
break;
case 'T': printf("Please enter your ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &ticketNumbers[0],&ticketNumbers[1],&ticketNumbers[2],&ticketNumbers[3],&ticketNumbers[4],&ticketNumbers[5],&ticketNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", ticketNumbers[0], ticketNumbers[1], ticketNumbers[2], ticketNumbers[3], ticketNumbers[4], ticketNumbers[5], ticketNumbers[6]);
break;
case 'C': printf("Computing....\n");
break;
case 'Q': printf("The program will now quit. Thank you for playing LOTO 649.\n");
return (0);
break;
default: printf("You entered an invalid option. The program will now terminate.\n");
return (0);
}
}
printf("The numbers are:%d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("The number is: %d\n", lotoNumbers[6]);
return 0;
}
You didn't allocate enough space for your arrays. The number used to allocate space for an array is the number of entries in the array, not the last index number. Index 6 is the 7th item and is past the end of the array. The value of lotoNumbers[6] is undefined and can change randomly, because the program is using that memory for something else.
int lotoNumbers[6];
int ticketNumbers[6];
That 6 should be 7.
Related
My array inside case 4 in looping Switch Menu doesn't print/display the value of the last array when the user input goes beyond array[4].
I tried to take the case 4 out and make it a single program to check if it doesn't really work on its own but it works fine, but when I put it back into the Switch, same issue again. I thought that maybe the initialization part is the problem. Help
`
#include <stdio.h>
int main ()
{
char first[20],last[20];
float math,eng,sci,avg;
int a,b,c,d,diff,array[diff],e,i,input;
do{
printf("\nMAIN MENU\n");
printf("[1] Basic Input Output\n[2] Conditional Statement\n[3] Looping Construct\n[4] Array\n[5] About\n[6] Exit");
printf("\n\nChoose: ");
scanf("%d",&input);
printf("\n");
switch (input)
{
case 1:
printf("\nEnter your given name:");
scanf("%s",first);
printf("Enter your surname:");
scanf("%s",last);
printf("\nHello %s %s!\n",first,last);
break;
case 2:
printf("\nEnter your grade in Math:");
scanf("%f",&math);
printf("\nEnter your grade in Science:");
scanf("%f",&sci);
printf("\nEnter your grade in English:");
scanf("%f",&eng);
avg=(math+eng+sci)/3;
if(math>eng&&sci)
{
printf("\nHighest grade is in: Math");
}
if(eng>math&&sci)
{
printf("\nHighest grade is in: English");
}
if(sci>eng&&math)
{
printf("\nHighest grade is in: Science");
}
if(math==eng)
{
printf("\n--Math and English tied grades--");
}
if(math==sci)
{
printf("\n--Math and Science tied grades--");
}
if(eng==sci)
{
printf("\n--Science and English tied grades--");
}
printf("\nYour average in 3 subjects:%f\n",avg);
break;
case 3:
printf("Enter beginning number: ");
scanf("%d",&b);
printf("Enter ending number: ");
scanf("%d",&c);
printf("\nCounting from %d to %d\n",b,c);
while(b<=c)
{
printf("%d ",b);
b++;
}
printf("\n");
break;
case 4:
printf("Enter Starting Series of Numbers: ");
scanf("%d",&a);
printf("Enter Ending Series of Numbers: ");
scanf("%d",&d);
diff=(d-a);
array[diff]=d;
printf("Select Array Value to Display: 0 to %d: ",diff);
scanf("%d",&e);
for(i=0;i<=diff;i++)
{
array[i]=a;
if(i==e)
{
printf("%d\n",array[i]);
}
a++;
}
break;
case 5:
printf("Abouts\n");
break;
case 6:
printf("Thank you!");
break;
}
}while(input != 6);
return 0;
}
`
This should be a comment, but I donĀ“t have enough reputation yet.
As Gerhardh said, the problem is that you use diff before being initialized (which causes undefined behaviour)
As you said, if you move the initialization of array inside the case 4: after diff being set the program should work as intended. If you want to keep it before the switch, try using int* and malloc/free inside the case 4: (and add #include <stdlib.h>) Anyway, you should check diff as positive value before using it to set the size of array
About optimizing the code, you can skip the line array[diff]=d; because you are setting the same value inside the for loop. And you can remove the line a++; if you changes array[i]=a; -> array[i]=a+i;
In this multiplication game, I have to generate two random numbers and multiply them. The user has to guess the right product. After the game, the user has a choice to either restart the game or quit (along with other choices to display/reset stats). I am required to use a switch-case structure for the choices the user decides on after the game. I also know I have to use a do-while loop for restarting/quitting the game but I don't know what to put in place of the bolded comments (after cases 1 and 3). Thanks in advance for taking the time to read. Any help is much appreciated!
#include <stdio.h>
#include <stlib.h>
#include <time.h>
#include <math.h>
int main () {
//Start do-while loop
do {
//Display rules of the game to the user.
printf("Two random numbers (1-12) will be generated and displayed. The objective of this game is to correctly guess the product of the numbers.");
//Generate two random integers between 1 and 12 and display them to the user
int i;
int n1;
int n2;
srand(time(NULL));
for(i = 1; i<=12;i++)
{
n1 = 1 + rand() % 12;
n2 = 1 + rand() % 12;
printf("The two random numbers generated are : %d and %d\n", n1,n2);
}
//Prompt the user to enter the product of the two numbers
int a;
printf("Enter the product of the two numbers: ");
scanf("%d", &a);
//Determine and display if or not the answer was right
int countCorrect;
int countIncorrect;
int product = n1*n2;
if (a == product)
{
printf("Correct response!");
countCorrect++;
}
else
{
printf("Incorrect response, the correct answer is: %d\n", product);
countIncorrect++;
}
//Start switch-case structure for post-game options
int choice;
switch (choice)
{
case 1:
printf("You have chosen to play again");
**//How do I restart the program so the user can play again?**
break;
case 2:
printf("You have chosen to see statistics");
printf("The number of correct answers are: %d\n", countCorrect);
printf("The number of incorrect answers are: %d\n", countIncorrect);
break;
case 3:
printf("You have chosen to reset statistics");
countCorrect = 0;
countIncorrect = 0;
break;
case 4:
printf("You have chosen to quit");
**//How do I quit the program?**
break;
default:
printf("Invalid number! Please enter a number from 1 to 4.");
break;
}
}
Several things that need to be fixed. When declaring variables, it's good practice to initialise them at the time of decleration. Rather than int a; a = x; And to only declare variables when needed. But this can obviously come down to preference and practice. In C89 variables had to be declared at the top of the scope but I can tell you're not compiling C89. You also didn't need to loop the rand 12 times. Just two calls is enough if you want two seperate ints. Keep in mind rand isn't very good but for practice it's okay. Placing a new line after print statement can make the output neater. countCorrect and countIncorrect were declared but not initialised to 0 then later incremented. This is bad practice because you don't know the initial value of either variable and you wouldn't get an accurate count.
I'm assuming you want to only quit when the user enters 4 but keep looping otherwise?
Place the switch outside the loop then after the user guesses the product, read the choice from the user and use that value the end of the do while loop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int guess(){
int x = 1+rand()%12;
int y = 1+rand()%12;
printf("The two random numbers generated are : %d and %d\n", x,y);
printf("Enter the product of the two numbers: ");
int z = 0;
scanf("%d", &z);
if(z == (x*y)){
printf("Correct response!\n");
return 1;
}
printf("Incorrect response, the correct answer is: %d\n", x*y);
return 0;
}
int main () {
srand(time(NULL));
printf("Two random numbers (1-12) will be generated and displayed. The objective of this game is to correctly guess the product of the numbers.\n");
int correct = 0;
int incorrect = 0;
int choice = 1;
do{
if(choice==1){
if(guess()){
++correct;
}else{
++incorrect;
}
}
printf("Enter 1 to play again\nEnter 2 to see statistics\nEnter 3 to reset statistic\nEnter 4 to quit:");
scanf("%d",&choice);
switch (choice) {
case 1:
break;
case 2:
printf("You have chosen to see statistics\n");
printf("The number of correct answers are: %d\n", correct);
printf("The number of incorrect answers are: %d\n", incorrect);
break;
case 3:
printf("You have chosen to reset statistics\n");
correct = 0;
incorrect = 0;
break;
case 4:
printf("You have chosen to quit\n");
break;
default:
printf("Invalid number! Please enter a number from 1 to 4.\n");
break;
}
}while(choice !=4);
return 0;
}
I am trying to teach myself C. For fun and for my own development, I have created a code that prompts the user for a letter grade, then outputs the range of that letter grade. Here is what I have so far:
//Ted C. Lim
#include "stdio.h"
int main()
{
char grade;
printf("Enter a single character grade: ");
scanf("%c", &grade);
printf("You entered %c as the grade. ", grade);
switch(grade)
{
case 'A':
printf("The grade range for A and A- is 100%% - 90%%.");
break;
case 'B':
printf("The grade range for B and B- is 80%% - 89%%.");
break;
case 'C':
printf("The grade range for C and C- is 70%% - 79%%.");
break;
case 'D':
printf("The grade range for D and D- is 60%% - 69%%.");
case 'F':
printf("The grade range for F is 0%% - 59%%.");
default:
printf("That grade does not exist.");
break;
}
}
If you run the program, you will see that it asks the user only once, returns the proper output, then stops. What I would like to do is repeat the prompt indefinitely until the user inputs something like 'Q' to quit. I know I should use some sort of loop here, but I'm not quite sure how to apply it.
There a couple different options you could choose here, both the while and the do while loop would work. Personally, I would say that a do while loop would be better fit for this case, mostly because you know for sure that you want the program to prompt the user at least once. In order to use it you would need to place the do before the printf statements and then run while some scanf input at the end is != "Q"
You can use a while loop, along with another character case to exit out of the loop.
char grade;
while (1)
{
printf("Enter a single character grade (or 'X' to exit): ");
scanf(" %c", &grade);
printf("You entered %c as the grade. ", grade);
if (grade == 'X') // Or another letter, make it clear what you're using
{
break;
}
// Output code here...
}
I would also recommend you check for both lowercase and uppercase letters. In the switch statement:
case 'A':
case 'a':
printf("The grade range for A and A- is 100%% - 90%%.");
break;
In the if statement:
if (grade == 'X' || grade == 'x')
{
break;
}
To repeat an action indefinitely, you could wrap it inside a while loop with a condition that is always true (e.g., while (1) { ... }) as follows:
#include <stdio.h>
#include <ctype.h>
int main()
{
char grade;
while (1)
{
printf("Enter a single character grade (or Q to quit):\n");
scanf(" %c", &grade);
grade = toupper(grade);
if (grade == 'Q') break;
printf("You entered %c as the grade.\n", grade);
switch(grade)
{
case 'A':
printf("The grade range for A and A- is 100%% - 90%%.\n");
break;
case 'B':
printf("The grade range for B and B- is 80%% - 89%%.\n");
break;
case 'C':
printf("The grade range for C and C- is 70%% - 79%%.\n");
break;
case 'D':
printf("The grade range for D and D- is 60%% - 69%%.\n");
break;
case 'F':
printf("The grade range for F is 0%% - 59%%.\n");
break;
default:
printf("That grade does not exist.\n");
break;
}
}
return 0;
}
You'll notice I've made a few other modifications, which I'll run through here:
include "stdio.h" should really be #include <stdio.h>. The angle brackets tell the compiler to look in the standard directory for system header files.
I also added #include <ctype.h> because I'm using the toupper() function to convert the input character to upper case. This makes your code easier to use, because it will now accept both upper and lower case letters.
The scanf() format string includes a space before %c. This will skip over any white space characters including newline characters. Without it, the program would treat these characters as actual inputs and tell you that the \n grade does not exist.
The break statement can be used to exit the loop when the user enters Q. There were also a couple of breaks missing from your switch block.
The main() function is declared as int main() { ... }, so it should return an integer value. If no errors have occurred, this value should be zero.
Encase your switch case inside of a while loop that is true and it will run indefinitely. You can also use scanf to check for a specific key to be entered to stop it too.
hello guys I coded something like kfc menu,and I got it to work(finally),but when I input something other than numbers for "menu",eg:the letter "A", I just can't get it to loop again to normal,instead it finishes the program
#include <stdio.h>
#include <stdlib.h>
int main()
{
char counter='y';
float totalprice=0;
while (counter=='Y' || counter=='y')
{
int menu;
float price=0;
printf("\nplease select from menu:");
scanf (" %i", &menu);
switch(menu)
{
case 1: {
printf("\none hotbox1 =RM10.50");
totalprice=totalprice+10.50;
break;
}
case 2: {
printf ("\none hotbox2=RM10.60");
totalprice=totalprice+10.60;
break;
}
case 3:{
printf ("\none hotbox3=RM10.70");
totalprice=totalprice+10.70;
break;
}
default : {
printf ("\nplease enter proper number please:");
scanf("%2f", &menu);
break;
}
}
printf("\n\nadd order?(Y/N):");
scanf (" %c", &counter);
}
printf("\n\nThe total price is: %f", totalprice);
return 0;
}
You should use fgets() (reference here) first and then sscanf() (reference here), checking it's return value to see if it's a number.
char inputBuffer[MAX_BUFFER];
do
{
fgets(inputBuffer, MAX_BUFFER, stdin);
}
while(sscanf(inputBuffer, "%d", &menu) != 1)
You scanf with %f in the default case, I am fairly certain that is for floats. Use %d.
Remove scanf("%2f", &menu);
Switch in C does not support char in switch-case. Before you start switch-case validate the user input. If it is a number go into switch case otherwise display a user message to enter only numeric value
I recommend that you debug this by printing out the value of "counter" at various points in the loop (i.e. after you read it in, at the bottom of the loop, etc.). This will give you visibility into what your code is doing.
You can try something like this
#include <stdio.h>
int main()
{
char counter;
float totalprice=0;
int menu=0;
do
{
printf("\n1. one hotbox1=RM10.50");
printf("\n2. one hotbox2=RM10.60");
printf("\n3. one hotbox3=RM10.70");
printf("\nplease select from menu:");
scanf ("%d", &menu);
switch(menu)
{
case 1:
printf("\none hotbox1 =RM10.50");
totalprice=totalprice+10.50;
break;
case 2:
printf ("\none hotbox2=RM10.60");
totalprice=totalprice+10.60;
break;
case 3:
printf ("\none hotbox3=RM10.70");
totalprice=totalprice+10.70;
break;
default :
printf ("\nplease enter proper number please:");
scanf("%d", &menu);
}
printf("\n\nadd more order?(Y/N):");
fflush(stdin); //to empty the input stream.
scanf("%c",&counter);
}while(tolower(counter) != 'n'); //tolower returns the lowercase character.
printf("\n\nThe total price is: %.2f", totalprice);
return 0;
}
When scanf("%i", &menu) tries to read an integer from the input, it finds A, which it cannot interpret as a number, so it does not read it(*). Then the next scanf continues reading the input from when the other left off and happily reads the letter 'A'. Since you loop as long as the read letter is either 'y' or 'Y' (which A is neither), it exits the loop.
(*) read up on the documentation of scanf to see how to tell if it encountered an error.
Note: scanf("%i", &menu) should be scanf("%d", &menu) as%d` is the formatting symbol for integers.
One solution would be to change the loop condition to:
while (counter!='N' && counter!='n')
{
...
}
This way you end the loop only if an explicit 'N' or 'n' is inputted.
Note: it won't help if you accidentally type 'n' for the menu item, so see the comment about the error handling above.
I am trying to store character as well as integer numbers in the same region through character pointer however, I am not getting the intended result. It is displaying only characters.
Here, I have created a character pointer which should contain atleast both characters and
integers, then should display them properly.
int main()
{
char c,store[30];
char *p=malloc(30);
int choice,i=0,n;
p=store;
while(1)
{
printf("\n********Menu**********");
printf("\n1.Enter a character");
printf("\n2.Enter a Number");
printf("\n3.Enter a double");
printf("\n4.Display the values");
printf("\n0.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter a character:");
fflush(stdin);
scanf("%c",&c);
*p=c;
p++;
break;
case 2:
printf("\nEnter a Number");
scanf("%d",&n);
*p++=n;
break;
case 4:
*p--='\0';
for(i=0;store[i];i++)
printf("%c",store[i]);
break;
case 0:
exit(0);
break;
}
}
getch();
return 0;
}
You can't simply write doubles and int into a char array.
However with following you could see 0-9 :
case 2:
printf("\nEnter a Number"); //Just for 0-9
scanf("%d",&n);
*p=n+48; //Convert to ascii
p++;
break;