Execute code for specific character values. - c

I'm currently taking the Video Game Programming course at the Art Institute of Vancouver, in my second quarter and I have a programming class. I'm currently stuck on a bit of homework and I'm unsure why. I'm a beginner when it comes to programming. I have experience with HTML, CSS and Javascript.
The problem I have involves creating a bill for a telephone service customer, but it is entirely dependant on the type of service they are using. The code needs to be executed if the service code they input is either 'r' or 'p', and any other input results in an error. However I'm unsure where to proceed after this.
`
int account, minutes1, minutes2;
char s;
float cost;
printf("Please enter your account number. \n");
scanf_s("%d" , &account);
if(account == -1)
return 0;
printf("Please enter your service code(r for regular or p for premium). \n"); /*checking service*/
scanf_s(" %s" , &s);
switch(s)
{ /*execute specific parameters when r or p are selected as service codes.*/
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o': printf("Error. Please choose a correct service code (r for regular or p for premium). \n");
break;
case 'p': printf("Please enter how many minutes you've used between 6am and 6pm. \n");
scanf_s("%d" , &minutes1);
if(minutes1 > 75)
minutes1 = (minutes1-75)*.10;
printf("Please enter how many minutes you've used between 7pm and 5am. \n");
scanf_s("%d" , &minutes2);
if(minutes2 > 100)
minutes2 = (minutes2-100)*.05;
cost = 25+minutes1+minutes2;
printf("Your account number is %d, your service code is premium, you used %d minutes during the day and %d minutes during the night and your bill comes to $%lf. \n", account, minutes1, minutes2, cost);
break;
case 'q':
case 'r': printf("Please enter how many minutes you've used. \n");
scanf_s("%d", &minutes1);
if(minutes1 > 55)
minutes1 = (minutes1-55)*.20;
cost = 10+minutes1;
printf("Your account number is %d, your service code is regular, you used %d minutes and your bill comes to %lf. \n");
break;
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': printf("Error. Please choose a correct service code (r for regular or p for premium). \n");
break;
}`

If you are scanning for character you should use scanf("%c",&s);
Also just use:
switch(s){
case 'p':
...
break;
case 'r':
...
break;
default:
error
}

Related

How to prompt the user to loop in C?

I’m new to C and currently doing a Jack ‘N Poy that requires the project to restart when the user prompt it like by answering y. However, I can’t seem to grasp its pattern. Have tried it on C++ and it worked but not on C. Can anyone help? I want the user to have the ability to play again after finishing the game.
Here is the code:
#include<stdio.h>
int main (){
char firstPlayer, secondPlayer, again;
do{
printf("Jack 'n Poy)\nEnter Player 1 input: ");
scanf("%c ", &firstPlayer);
printf("Enter Player 2 input: ");
scanf("%c", &secondPlayer);
switch (firstPlayer){
case 'x':
switch (secondPlayer){
case 'x':
printf("Draw");
break;
case 's':
printf("Player 2 wins");
break;
case 'p':
printf("Player 1 wins");
}
break;
case 's':
switch (secondPlayer){
case 'x':
printf("Player 1 wins");
break;
case 's':
printf("Draw");
break;
case 'p':
printf("Player 2 wins");
}
break;
case 'p':
switch (secondPlayer){
case 'x':
printf("Player 2 wins");
break;
case 's':
printf("Player 1 wins");
break;
case 'p':
printf("Draw");
}
break;
default:
printf("Invalid input");
}
printf("\nPlay again? (y/n)");
scanf("%c", &again);
}
while (again == 'y');
printf("Thank you for playing");
return 0;
}
Have also tried adding a substitute variable for the y and yes it does loop, but the loop skips the first question.
Your help are very much appreciated. Thank you very much!
You need to change the format to:
scanf(" %c", ...);
in all scanfs. Note the ' ' before %c
Your again is a string. You can use strcmp(expectedString,inputString) as the condition at while. You will need to include the string.h header file to be able to do this.
Alternatively, change again to char type, i.e. char again;
And then use %c in the last scanf, i.e. scanf("%c", &again);. You may face skipped character scenario if spaces or newlines are entered. In that case, refer to this answer for guidance.

Im having a problem with a while loop and switch

while(Game == 0)
{
gotoxy(100,40);
setForeColor(MY_COLOR_WHITE);
printf("A- Jogar uma partida de Anabi\n");
gotoxy(100,42);
printf("B- Carregar partida anterior\n");
gotoxy(100,44);
printf("C- Descri%c%co do jogo\n", 135, 198);
gotoxy(100,46);
printf("D- Sair do jogo\n");
scanf("%c", &choice);
switch(choice)
{
//This part of the code should break my loop
case 'A':
case 'a':
gotoxy(100, 52);
printf("Please enter your name bellow\n");
gotoxy(98, 53);
printf("->");
scanf("%s",NamePlayer);
Game = 1;
break;
case 'B':
case 'b':
// in here I am going to call a function, the function that reads the file previously saved
//also here I am going to know if there is any saved files, and give an output to the user
break;
case 'C':
case 'c':
//This gets me to the description of the game, rules, etc.. and its working fine with the loop
DescricaoDoJogo();
break;
case 'D':
case 'd':
exit(0);
break;
default:
//This default is giving me trouble, should I use and If, else? Because when i choose the option C, and I get back to the menu what is inside the default executes
printf("Wrong choice.. Try again.. A, B, C or D..");
scanf(" %c", &choice);
system("cls");
break;
}
}

why does "type mismatch in redeclaration of hexadecimal" keep popping up?

I am a totally newbie about C programming. so my program is very long, sorry.
my professor wants to have a number system- binary to decimal, decimal to binary, octal to decimal, hexadecimal to binary. he also want to have a loop( if he wants to exit press [E], if not then press any key). Now i'm having a problem with this hexadecimal because it keeps saying " type mismatch in redeclaration" and i don't know now how to solve this problem.
so heres my not yet finished program because of "hexadecimal" problem. help me with this error. don't mind the octal to decimal, I am currently programming it :)
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 1000
long num, decimal(long), octal(long), binary(long),j;
char hexadecimal(char), k[MAX];
main()
{
char choice;
clrscr();
printf("[B]inary to Decimal\n");
printf("[D]ecimal to Binary\n");
printf("[O]ctal to Decimal\n");
printf("[H]exadecimal to Binary\n");
printf("[E]xit\n");
printf(" Enter your choice....");
choice=getche();
switch(choice)
{
case 'b':
case 'B': binary(j); break;
case 'd':
case 'D': decimal(num); break;
case 'o':
case 'O':
case 'h':
case 'H': hexadecimal(k[MAX]); break;
case 'e':
case 'E': return 0;
default: printf("\n Invalid choice.... press any key to REPEAT");
getch();
main();
}
printf("\nDo you want to [E]xit?");
choice=getch();
switch(choice)
{
case 'e':
case 'E': printf("\nInvalid choice... press any key to repeat");
getch();
main();
}
getch();
return 0;
}
long binary(long j)
{
long binary_val,decimal_val=0, base=1, rem;
printf("Enter a binary number( 1s & 0s): ");
scanf("%ld",&j);
binary_val=j;
while(j>0)
{
rem=j % 10;
decimal_val=decimal_val + rem * base;
j= j/ 10;
base=base * 2;
}
printf(" The Binary Number is %ld\n",binary_val);
printf(" Its decimal equivalent is = %d\n",decimal_val);
}
long decimal(long num)
{
long decimal_num, remainder, base=1, binary=0;
printf(" \nEnter a decimal integer: ");
scanf("%ld",&num);
decimal_num=num;
while(num>0)
{
remainder= num % 2;
binary=binary + remainder * base;
num=num/2;
base= base * 10;
}
printf(" Input number is %d\n",decimal_num);
printf(" Its binary equivalent is = %ld",binary);
}
char hexadecimal(char k[MAX])
{
long int i=0;
clrscr();
printf(" Enter any Hexadecimal number: ");
scanf("%s",&k);
printf("\n Equivalent binary value: ");
while(k[i])
{
switch(k[i])
{
case '0': printf("0000"); break;
case '1': printf("0001"); break;
case '2': printf("0010"); break;
case '3': printf("0011"); break;
case '4': printf("0100"); break;
case '5': printf("0101"); break;
case '6': printf("0110"); break;
case '7': printf("0111"); break;
case '8': printf("1000"); break;
case '9': printf("1001"); break;
case 'a':
case 'A': printf("1010"); break;
case 'b':
case 'B': printf("1011"); break;
case 'c':
case 'C': printf("1100"); break;
case 'd':
case 'D': printf("1101"); break;
case 'e':
case 'E': printf("1110"); break;
case 'f':
case 'F': printf("1111"); break;
default: printf("\n Invalid hexadecimal digit %c",k[i]); return 0;
}
i++;
}
}
The error you are getting type mismatch in redeclaration of hexadecimalis a result of the difference between the function you prototyped and implemented.
Your prototype is:
char hexadecimal(char), k[MAX];
This line prototypes a function hexadecimal that returns a char and takes a char as an argument AND this line also declares a global char array k of size MAX.
Your actual function is:
char hexadecimal(char k[MAX])
This function is a function that returns a char, but instead of taking a char like your prototype it instead takes a char array of size MAX. As you can see the prototyped function and the function itself are not the same. By making the functions exactly the same you will fix your issue.
To be honest, you don't need to pass anything into that function nor make a global char array as you can locally hold the array based on your code. The only other time you use the array you just pass it to this function which means it is better of as a local to that function anyway. So, you can simply do this:
char hexadecimal(void)
{
char k[MAX]
//same code below...
Now the function takes no arguments and k is still declared in the function, but is local instead of global. The prototype for this function would simply be:
char hexadecimal(void);

Basic C Programming : Run-Time Check Failure #3 - The variable 'pro1' is being used without being initialized

I am a newbie to Computer Science and I'm currently studying first year in university.
I have a problem when comes to one question today.
The question is this :
Write a program to allow the user to enter code and quantity sold for 3 products (use different variables to store these 5 different product codes). Your program is required to calculate the total amount for each product (quantity x unit price) and the grand total of all products sold.
At the end, your program will display product code, product description, unit price and total amount for each product and also the grand total amount for all the products sold. Use the information on the following table as reference:
PS: you will be expected to have many variables used and many redundant of same codes appear in your program which is fine, because no looping is needed to apply here.
Extra requirements :
Set the price to 2 decimal points
Fix the product code using constant method.
Use switch statement to get for the product price.
Include 6% tax calculation in the grand total.
Here is my answer, it is run with no error when I compile the code, but when I try to run it, it has the problem stated :
Run-Time Check Failure #3 - The variable 'pro1' is being used without being initialized.
My answer code :
#include <stdio.h>
int main()
{
float pro1, pro2, pro3, pro4, pro5;
float subtotal, Tax, total;
int unit;
char code;
int x, y, z, a, b;
printf("Enter the quantity of the product.\n");
scanf("%d", &unit);
printf("Enter the product code.(x=12345,y=56789,z=45678,a=13579,b=34567)\n");
scanf("%d", &code);
switch (code)
{
case 'x':
pro1 = unit*3.50;
break;
case 'y':
pro2 = unit*3.50;
break;
case 'z':
pro3 = unit*1.20;
break;
case 'a':
pro4 = unit*4.50;
break;
case 'b':
pro5 = unit*1.00;
break;
default:
printf("Invalid code.\n");
break;
}
printf("Enter the quantity of the product.\n");
scanf("%d", &unit);
printf("Enter the product code.(x=12345,y=56789,z=45678,a=13579,b=34567)\n");
scanf("%d", &code);
switch (code)
{
case 'x':
pro1 = unit*3.50;
break;
case 'y':
pro2 = unit*3.50;
break;
case 'z':
pro3 = unit*1.20;
break;
case 'a':
pro4 = unit*4.50;
break;
case 'b':
pro5 = unit*1.00;
break;
default:
printf("Invalid code.\n");
break;
}
printf("Enter the quantity of the product.\n");
scanf("%d", &unit);
printf("Enter the product code.(x=12345,y=56789,z=45678,a=13579,b=34567)\n");
scanf("%d", &code);
switch (code)
{
case 'x':
pro1 = unit*3.50;
break;
case 'y':
pro2 = unit*3.50;
break;
case 'z':
pro3 = unit*1.20;
break;
case 'a':
pro4 = unit*4.50;
break;
case 'b':
pro5 = unit*1.00;
break;
default:
printf("Invalid code.\n");
break;
}
printf("Enter the quantity of the product.\n");
scanf("%d", &unit);
printf("Enter the product code.(x=12345,y=56789,z=45678,a=13579,b=34567)\n");
scanf("%d", &code);
switch (code)
{
case 'x':
pro1 = unit*3.50;
break;
case 'y':
pro2 = unit*3.50;
break;
case 'z':
pro3 = unit*1.20;
break;
case 'a':
pro4 = unit*4.50;
break;
case 'b':
pro5 = unit*1.00;
break;
default:
printf("Invalid code.\n");
break;
}
printf("Enter the quantity of the product.\n");
scanf("%d", &unit);
printf("Enter the product code.(x=12345,y=56789,z=45678,a=13579,b=34567)\n");
scanf("%d", &code);
switch (code)
{
case 'x':
pro1 = unit*3.50;
break;
case 'y':
pro2 = unit*3.50;
break;
case 'z':
pro3 = unit*1.20;
break;
case 'a':
pro4 = unit*4.50;
break;
case 'b':
pro5 = unit*1.00;
break;
default:
printf("Invalid code.\n");
break;
}
printf("Artline 500A Black (Whiteboard Marker): %f", pro1);
printf("Artline 500A Red (Whiteboard Marker): %f", pro2);
printf("Pocket File (Yellow): %f", pro3);
printf("Pencil Casing: RM %f", pro4);
printf("A4 Exercise Book: %f", pro5);
subtotal = pro1 + pro2 + pro3 + pro4 + pro5;
Tax = subtotal*0.06;
total = subtotal + Tax;
printf("Subtotal : %f", subtotal);
printf("Tax : %f", Tax);
printf("Total : %f", total);
system("pause");
return 0;
}
I have only learned so far about basic I/O operations, if-else statements and switch case statements.
Imagine all your switch statements go through the defaultcase, and you hit the printf() with pro.
Certainly a read before write scenario for an uninitialized automatic local variable will cause undefined behavior in your application, as the value your're trying to read is indeterminate.
Suggestion: Always initialize your local variables.
What value has pro1 if the user never gave x as the code? Then pro1 is never assigned a value--which in C lingo means it is uninitialized when the control reaches
subtotal = pro1 + pro2 + pro3 + pro4 + pro5;
If the intent is to use 0 for products that aren't used, you should initialize them with
float pro1 = 0, pro2 = 0, pro3 = 0, pro4 = 0, pro5 = 0;
Important: there's another bug in
char code;
scanf("%d", &code);
code must be an int if you scan with a %d format. Turn on all the warnings of your compiler! In addition, you must test the return of scanf with
if (scanf("%d", &code) != 1) {
/* error: could not convert the input to a number. */
}
Not checking the return from scanf is a sure recipe for surprises.
There are many issues with your code:
You are violating the DRY principle in a way that is actually exagerated.
You never check the return value from scanf() that could lead to the variable keeping it's previous value or being uninitialized when you use it.
You print the value of the probN variables but it might happen that the user never inputs the code for the Nth product.
You should initialize them to 0, because if the value was never inserted by the user it means that "no units" were sold.
Your switch statement will never work, if you input x with the "%d" specifier the second point of these 4 points will be a problem because code will be uninitialized when you reach the switch, you should use the "%c" specifier instead and check the value returned by scanf() to be sure that something was scanned.
So instead of
scanf("%d", &code);
you need
if (scanf(" %c", &code) != 1)
wow_this_is_really_unexpected_but_I_am_glad_to_be_careful();
it's also wrong to pass a char * when using the "%d" specifier, and it's actually a serious bug.
Initialize your variables,
float pro1=0, pro2=0, pro3=0, pro4=0, pro5=0;
It can happen that these variables are used without any value set during the switch statements if it falls through default case.

using switch case, error on the default part

although default part mustn't run,
it runs al case, I thanks for all helps at now, what should i do? This code all runs i writes on screen default case.
do
{
scanf("%c",&choice);
switch(choice)
{
case 'T':
printf("Enter edges of Triangle1\n");
scanf("%d%d",&edge1,&edge2);
Triangle1(edge1,edge2);
break;
case 't':
printf("Enter edges of Triangle1\n");
scanf("%d%d",&edge1,&edge2);
Triangle2(edge1,edge2);
break;
case 'R':
printf("Enter edges of square\n");
scanf("%d%d",&edge1,&edge2);
Rectangle(edge1,edge2);
break;
case 'S':
printf("Enter one edge of square\n");
scanf("%d",&edge);
Square(edge);
break;
case 'C':
printf("Enter radius of circile\n");
scanf("%d",&radius);
Circle(radius);
break;
default:
printf("Wrong input\n");
break;
}//end of switch
printf("\n");
}while(choice!='e');
The newline gets passed as well as input. Try calling "getc(stdin)" after the first scanf() and it should work :)
Check out for example: http://home.datacomm.ch/t_wolf/tw/c/getting_input.html#newline

Resources