Switch statement letter to integer - c

Assume that grades from A to F correspond to numbers from 1 to 6. Write a program that has three letter grades as inputs and prints the average numerical grade. My code looks like this : PS: I want this to print out the average of three letter inputs. (I take into account this code could be completely wrong, thus the final code should contain the "switch" and the calculation of the three corresponding values in numbers/interger. please help).
int main(){
char x,y,z;
int num;
float avg;
printf("\n Give three grades:\n");
scanf("%d %d %d", &x, &y, &z);
switch(x,y,z){
case 'a': return 1;
break;
case 'b': return 2;
break;
case 'c': return 3;
break;
case 'd': return 4;
break;
case 'e': return 5;
break;
case 'f': return 6;
break;
}
avg = x+y+z /3;
printf("\n The average is: %d \n", avg);
return 0;
}`

You can only switch on one value at a time. Why don't you make it a function:
int grade_value( char grade )
{
switch(grade) {
case 'a':
case 'A':
return 1;
case 'b':
case 'B':
return 2;
// etc...
default:
return 0;
}
}
Then just call it for each of x, y, and z. You really don't need to use a switch at all, but nevermind. eg
int grade_value( char grade )
{
int value = tolower(grade+1) - 'a';
return (value >= 1 && value <= 6) ? value : 0;
}
Also, note that you should use %f to output a float, not %d (which outputs an int).
You've also misunderstood how switch works. In your main, you switched and return from each case. That would exit main and return a value. That means your program would terminate.
You can use return in the function I suggested for you, because it's not your main. It will immediately return the given value from the function, thus you don't need `break'.

Related

I keep getting a segmentation fault in my C code

First off, I am relatively new to C programming, and wanted to write a program that would be able to accept user input and then pass that on to a switch/case and return output based on the initial choice. I was able to do this while using the int data type, but I would like some help doing the same while taking input as a char.
#include <stdio.h>
double x = 1;
double y = 3;
char inputLet[1];
double chooseEquation(char notLet){
char notNotLet = notLet;
printf("notLet here is: %c \n", notLet);
switch(notLet){
case 'A':
x += y;
printf("Case1 reached! \n");
break;
case '2':
x += -y;
break;
case '3':
x -= y;
break;
case '4':
x -= -y;
break;
case '5':
x *= y;
break;
case '6':
x *= -y;
break;
default :
printf("defaulting! btw: %c \n", notNotLet);
x = 0;
}
printf("x has been set? Here: %.2f\n", x);
return x;
}
int main(){
printf("Welcome, please pick a letter from A to F (uppercase for now) in order to choose an equation: \n");
scanf(" %c", &inputLet);
printf("The letter you chose is: %s \n", inputLet);
double outputLet = chooseEquation(inputLet);
printf("Your equation evaluated to: %.2f \n", outputLet);
return 0;
}
Somehow, no matter the input, the character that the switch looks at becomes Q
However, if I replace this line:
char inputLet[1];
with this line:
char inputLet;
The program segmentation faults.
Any help would be much appreciated.
printf("The letter you chose is: %s \n", inputLet);
When you use char inputLet then use %c. This is causing the error.
And also if it is a single character then just use char inputLet not a character array.
After changing it, I tested it locally and got this output for 'A'
Welcome, please pick a letter from A to F (uppercase for now) in order to choose an equation:
A
HelloThe letter you chose is: A
notLet here is: A
Case1 reached!
x has been set? Here: 4.00
Your equation evaluated to: 4.00

C: can't figure out what is causing an infinite loop

I'm a beginner, and as an exercise I have to code a very simple calculator that modifies the stack by the number and the operator the user inputs.
This is the code:
#include <stdio.h>
int main (void)
{
long double x, stack = 0;
char op;
printf("Input an operator and a number:\n");
while ( op != 'q' )
{
scanf("%Lf %c", &x, &op);
switch (op)
{
case '+':
stack += x;
printf("= %Lg", stack);
printf("\n");
break;
case '-':
stack -= x;
printf("= %Lg", stack);
printf("\n");
break;
case '*':
stack *= x;
printf("= %Lg", stack);
printf("\n");
break;
case '/':
if (x == 0)
{
printf("Can't divide by 0.");
printf("\n");
break;
}
stack /= x;
printf("= %Lg", stack);
printf("\n");
break;
case 's':
stack = x;
printf("stack set to %Lg", x);
printf("\n");
break;
case 'q':
printf("Bye!\n");
break;
default:
printf("Unknown operator.\n");
break;
}
}
printf("Bye!\n");
return 0;
}
Now the problem is that whenever x is not an number, the program keeps looping. Why?
And how could I prevent the user from inputing anything but a number for x? If x was a char I'd use isdigit(), but that's not the case.
(By the way, I want x to be a long double so I can input numbers with decimals).
scanf() will convert as many values from the string as it can. If one cannot be converted, it stops processing the string. Either way, the function returns a value indicating how many values were converted.
If the first value (x) is not a number and cannot be converted, it stops. And so the second value (op) does not change. That causes your loop to continue.
Check the value returned by scanf() to confirm this behavior yourself.
Also, "I want x to be a long double so I can input numbers with decimals" - Values of type float and double also support numbers with decimals.
Finally, as others have point out, you should initialize op at the start of your code before testing if it equals "q". This will ensure the value is what you expect it to be at that time.

Beginners switch case action is always default

i have just entered a switch case code.. i don't understand why when i am pressing '1', it is still going to the default case always.
#include <stdio.h>
int main() {
char c = 0;
int x = 0, y = 0;
printf("Please write 2 numbers:\n");
scanf("%d %d", &x, &y);
printf("Please choose an action from the math menu:\n\n1.add\n2.sub\n");
scanf(" %c", &c);
switch (c)
{
case 1:
printf("%d + %d is %d\n", x, y, x+y);
break;
default: printf("Wrong value\n");
break;
}
return 0;
}
As c is declared as having character type then entered 1 and 2 are characters correspondingly '1' and '2'.
So write
switch (c)
{
case '1':
printf("%d + %d is %d\n", x, y, x+y);
break;
case '2':
printf("%d - %d is %d\n", x, y, x-y);
break;
default: printf("Wrong value\n");
break;
}
The character 0 to 9 are actually ascii values 48 to 57. switch( (int)(c-48) ) would work. The express (int)(c-48) changes the ascii digits to integers.
An alternative to the previous answer using character literals:
switch(c)
{
case '1':
...
break;
...
}
This allows you to even handle 'q' and the like.
When doing 'q', keep in mind the case sensitivity:
switch(c)
{
case 'q':
case 'Q':
... handle q
break;
}
In short: You are reading a char, treat it as a char.

C - Issue converting a user generated number into words

So I've been working my way through Kochan's Programming in C and I've hit a snag on one of the questions which reads as follows:
"Write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. So if the user types in 932, the program should display the following: nine three two (Remember to display zero if the user types in just 0.)"
I had managed to get the program to print out the digits as words but unfortunately in reverse order. From there I thought it might be a good idea to reverse the number so to speak, but now when I run that value through my program only prints out "one one one ...." for how ever many digits long the number I enter in.
In other words, originally I managed to display 932 as "two three nine", but when I tried to reverse the number and run 239 through my program I only get "one one one".
If any one has any hints that could point me in the right direction it would be very much appreciated! My code is below:
#include <stdio.h>
int digitCount (int);
int reverseNumber (int);
int main(void)
{
//Chapter 6 Problem 6
int x, numberValue;
printf("Enter the number you'd like converted to words\n");
scanf("%i", &x);
numberValue = reverseNumber(x);
printf("The reverse is %i\n", numberValue);
do {
numberValue = numberValue % 10;
switch (numberValue) {
case 0:
printf("zero\t");
break;
case 1:
printf("one\t");
break;
case 2:
printf("two\t");
break;
case 3:
printf("three\t");
break;
case 4:
printf("four\t");
break;
case 5:
printf("five\t");
break;
case 6:
printf("six\t");
break;
case 7:
printf("seven\t");
break;
case 8:
printf("eight\t");
break;
case 9:
printf("nine\t");
break;
default:
break;
}
x = x / 10;
} while (x != 0);
return 0;
}
int digitCount (int u)
{
int cnt = 0;
do {
u = u / 10;
cnt++;
} while (u != 0);
return cnt;
}
int reverseNumber (int y)
{
int cnt, Rev;
cnt = digitCount(y); //returns number of digits
while (cnt != 0) {
Rev = Rev * 10 + y % 10;
y = y / 10;
cnt--;
}
return Rev;
}
In your reverseNumber function you have not initialized Rev. Make Rev=0
int reverseNumber (int y)
{
int cnt, Rev=0;
cnt = digitCount(y); //returns number of digits
printf("Digit count %d\n", cnt);
while (cnt != 0) {
Rev = Rev * 10 + y % 10;
y = y / 10;
cnt--;
}
return Rev;
}
In main in the do while loop use a temporary variable since you are overwriting numberValue with numberValue % 10. But the most ironic part in your program (where you complicated everything for yourself) is that there is no need to reverse the number at all. See the code here
In the way user entered - http://ideone.com/pORaP2
In reverse order - http://ideone.com/5GS8al
When you find modulo you get the number in the reverse order itself. Suppose you entered 234
First step 234%10 gives 4 prints four. And then makes 234 to 23
Second step 23%10 gives 3 prints three. And then makes 23 to 2
and then finally prints two.
Consider what the primary problem is you are dealing with, you need to process the left most digit first, then the next to the right, then the next. But the math of using modulus and division goes from right to left. So what you need is some way to either save the math processing and reverse, or have the output be delayed. Two options are available.
For an iterative approach you could utilize a FIFO queue type approach that holds the results of each digit and then prints out the queue. Could be as simple as an array with indexing:
int main(void) {
int x, i;
int result[32]; //arbitrary size
int index = 0;
printf("Enter the number you'd like converted to words\n");
scanf("%i", &x);
do {
results[index++] = x % 10;
x = x / 10;
} while( index < 32 && x != 0 );
//now print in reverse order
for(i = index-1; i >= 0; i--) {
switch (results[i]) {
case 0:
printf("zero\t");
break;
case 1:
printf("one\t");
break;
case 2:
printf("two\t");
break;
case 3:
printf("three\t");
break;
case 4:
printf("four\t");
break;
case 5:
printf("five\t");
break;
case 6:
printf("six\t");
break;
case 7:
printf("seven\t");
break;
case 8:
printf("eight\t");
break;
case 9:
printf("nine\t");
break;
default:
break;
}
}
}
There is second approach that works which is recursive. Here you delay the printing of the output until you reach the left most digit. The built in stack is used for by the recursive calls.
void printNumbers(int x);
int main(void) {
int x;
printf("Enter the number you'd like converted to words\n");
scanf("%i", &x);
printNumbers(x);
}
void printNumbers(int v) {
if( v > 9 ) {
printNumbers( v / 10 );
}
switch (v%10) {
case 0:
printf("zero\t");
break;
case 1:
printf("one\t");
break;
case 2:
printf("two\t");
break;
case 3:
printf("three\t");
break;
case 4:
printf("four\t");
break;
case 5:
printf("five\t");
break;
case 6:
printf("six\t");
break;
case 7:
printf("seven\t");
break;
case 8:
printf("eight\t");
break;
case 9:
printf("nine\t");
break;
default:
break;
}
}
Both approaches will solve the problem, but not if the input is a negative number.
My simple answer:
void printNum(int x)
{
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}

How to have a C program respond to a letter and spit out something else?

I can't seem to get this program to compile.
I keep getting the error:
'Ammonia' undeclared 'Carbon_Monoxide' undeclared
and so on. Am I using the right function with switch?
/*This program will report the content of a compressed-gas cylinder based on the first letter of the cylinder's color.*/
#include <stdio.h>
int main (void)
{
int x;
char o, b, y, g;
int pause;
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%d", &x);
switch (x)
{
case 'o': printf("The content is Ammonia\n");
case 'b': printf("The content is Carbon Monoxide\n");
case 'y': printf("The content is Hydrogen\n");
case 'g': printf("The content is Oxygen\n");
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf("%d", &pause);
return 0;
}
It has nothing to do with your switch statement, but you will probably have to puzzle over the meaning of these four lines:
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
You don't use the variables thus defined anywhere, and the symbols "Ammonia", "Carbon_Monoxide" and so on are not defined - this is the cause of the error you are seeing.
Since this is homework, I don't want to give you the answer straight, but look at what you're doing with those chars (o, b, y, g) and ask yourself if it makes sense.
Also, on the switch statement, I'm pretty sure you need a break; after each case, else it will print each case's statement
try:
#include <stdio.h>
int main (void)
{
char x;
int pause;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%c", &x);
while(x){
switch (x)
{
case 'o': printf("The content is Ammonia\n"); break;
case 'b': printf("The content is Carbon Monoxide\n"); break;
case 'y': printf("The content is Hydrogen\n"); break;
case 'g': printf("The content is Oxygen\n"); break;
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf(" %c", &x);
if(x == 'q'){
break;
}
}
return 0;
}

Resources