So this is the code I'm working on. All is good except that I need to match the case with the counter so I can manage to display the desired output "you are in your tens / teens". I tried many different approaches but I couldn't get it right. However, I think the problem is within the condition. Any tips? Note: I'm just a beginner who just started programming in C this semester!
#include <stdio.h>
int main()
{
int YoB, CY, Age;
unsigned int counter = 0;
printf("Please enter your year of birth");
scanf_s("%d", &YoB);
printf("Please enter the current year");
scanf_s("%d", &CY);
Age = CY - YoB;
printf("Entered year of birth %d\n", YoB);
printf("Entered current year %d\n", CY);
printf("You are %d years old\n \n", Age);
if (Age > 18) {
puts("You are an adult\n");
if (Age < 18)
puts("You are a minor\n");
}
if(Age<=100){
while (++counter <= 10);
}
switch (counter) {
case 0:
puts("You are less than 10\n");
break;
case 1:
puts("you are in your tens / teens\n");
break;
case 2:
puts("You are in your twenties\n");
break;
case 3:
puts("You are in your thirties\n");
break;
case 4:
puts("You are in your fourties\n");
break;
case 5:
puts("You are in your fifties\n");
break;
case 6:
puts("You are in your sixties\n");
break;
case 7:
puts("You are in your seventies\n");
break;
case 8:
puts("You are in your eighties\n");
break;
case 9:
puts("You are in your nineties\n");
break;
case 10:
puts("You are a 100+!!\n");
break;
default:
puts("invalid age!");
break;
}
return 0;
}
Answer to your problem
You have a simple logic issue in your "counter-setter-loop" (I don't know how I should call this).
if(Age<=100){
while (++counter <= 10);
}
you're incrementing counter to 11 not 10. Suppose counter is 10, it'll iterate again, since the condition <= 10 is still true. As a result you'd need to change this part to:
if(Age<=100){
while (++counter < 10);
}
Code review
Anyway, when I saw your code, some code improvements went through my head. I hope that's fine for you, if not, you can skip this.
adding \n to printf (little UI improvement)
In my opinion it looks a little bit better, if you create a little prompt and create a new line for the input:
printf("Please enter your year of birth\n>> ");
scanf_s("%d", &YoB);
printf("Please enter the current year\n>> ");
scanf_s("%d", &CY);
Logic issue:
There's a logic issue in this part:
if (Age > 18) {
puts("You are an adult\n");
if (Age < 18)
puts("You are a minor\n");
}
Assuming Age is < 18. I think that you'd expect to have the output You are a minor. But this will never happen because in order to get to the if (Age < 18) condition, you'd need to enter the Age > 18 condition. So I think you mean it like that:
// Also keep in mind that Age can be "< 0" if the user used a "bad" input.
if (Age < 0) {
puts("You are not born yet.");
} else if (Age >= 18) {
puts("You are an adult\n");
} else {
puts("You are a minor\n");
}
Set counter a value instead of using a loop
You can change this part:
if (Age <= 100){
while (++counter <= 10);
}
to this:
if (Age <= 100) {
counter = 10;
}
although I don't really understand how you can enter the other case-arms since counter seems to be only 0 or 10 due to the condition above. I think you rather mean something like this:
if (Age <= 100) {
counter = Age / 10;
}
Also please use variable-names which start with a lowercase and not with a uppercase since uppercase Names are rather used for structs, enums or constants etc.
To sum it up, I'd do it as follows:
#include <stdio.h>
int main()
{
int birth_year, current_year, age;
unsigned int tenths = 0;
printf("Please enter your year of birth\n>> ");
scanf_s("%d", &birth_year);
printf("Please enter the current year\n>> ");
scanf_s("%d", ¤t_year);
age = current_year - birth_year;
printf("Entered year of birth %d\n", birth_year);
printf("Entered current year %d\n", current_year);
printf("You are %d years old\n \n", age);
if (age < 0) {
puts("You aren't born yet.");
} else if (age >= 18) {
puts("You are an adult.\n");
} else {
puts("You are a minor.\n");
}
if(age <= 100){
tenths = age % 10;
}
switch (tenths) {
case 0:
puts("You are less than 10\n");
break;
case 1:
puts("you are in your tens / teens\n");
break;
case 2:
puts("You are in your twenties\n");
break;
case 3:
puts("You are in your thirties\n");
break;
case 4:
puts("You are in your fourties\n");
break;
case 5:
puts("You are in your fifties\n");
break;
case 6:
puts("You are in your sixties\n");
break;
case 7:
puts("You are in your seventies\n");
break;
case 8:
puts("You are in your eighties\n");
break;
case 9:
puts("You are in your nineties\n");
break;
case 10:
puts("You are a 100+!!\n");
break;
default:
puts("invalid age!");
break;
}
return 0;
}
Related
From the book "Programming in C"
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
nine three two
Remember to display “zero” if the user types in just a 0.
Its been hours and its still cant be solved.. Do anyone know how to? This is the code so far
#include <stdio.h>
int right_digit,number;
int main ()
{
scanf("%i",&number);
right_digit = number % 10;
switch (right_digit)
{
case '0':
printf("0");
break;
case '1':
printf("one");
break;
case '2':
printf("two");
break;
case '3':
printf("three");
break;
case '4':
printf("four");
break;
case '5':
printf("five");
break;
case '6':
printf("six");
break;
case '7':
printf("seven");
break;
case '8':
printf("eight");
break;
case '9':
printf("nine");
break;
default:
break;
}
number = number / 10;
return 0;
}
The first problem here is, you're (wrongly) trying to use the character representation of the integer numbers. In your code, right_digit is supposed to represent an integer digit, not a character literal.
You must not to use the ''s, just write
case 0:
...
case 1:
and so on.
Just to add a bit on your mistake, it was considering the corresponding integer values of the character literal '0', '1' and so on. For ASCII, they are equivalent to
case 48:
case 49:
.
.
which is not what you intended.
That said,
You need to put the modulo calculation and switch-case inside a loop and carry out the conversion for all the digits of the input integer.
You need to start printing from the beginning (MSB), currently , you're printing from LSB. (Hint: Start printing the result of the modulo operation)
printf("0"); should be printf("Zero ");, as per the requirement.
/*USING SWITCH CASE ...ALSO YOU CAN USE '0' and negative numbers */
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int rem,num,sum=0,rem1,num1,add;
printf("enter the number:\n");
scanf("%i",&num);
if(num<0)
{
printf("minus ");
num=-num;
}
if(num==0)
{
printf("zero");
}
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10 +rem;
}
/*printf("%i\n",sum);*/
while(sum!=0)
{
rem1=sum%10;
sum=sum/10;
switch(rem1)
{
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
default:
printf("invalid no");
}
}
return 0;
}
Hope this program will help you to understand the logic and I am also posting the solution for same problem using switch case....
/* 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 >>> nine three two <<<.
* (Remember to display “zero” if the user types in
* just a 0.)
*/
/*USING IF-ELSE IF*/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int rem,num,sum=0,rem1;
printf("enter the number:\n");
scanf("%i",&num);
if(num<0)
{
printf("minus ");
num=-num;
}
if(num==0)
{
printf("zero");
}
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10 +rem;
}
/*printf("%i\n",sum);*/
while(sum!=0)
{
rem1=sum%10;
sum=sum/10;
if(rem1==0)
{
printf("zero ");
}
else if(rem1==1)
{
printf("one ");
}
else if(rem1==2)
{
printf("two ");
}
else if(rem1==3)
{
printf("three ");
}
else if(rem1==4)
{
printf("four ");
}
else if(rem1==5)
{
printf("five ");
}
else if(rem1==6)
{
printf("six ");
}
else if(rem1==7)
{
printf("seven ");
}
else if(rem1==8)
{
printf("eight ");
}
else if(rem1==9)
{
printf("nine ");
}
else
{
printf("invalid no");
}
}
return 0;
}
I'm making this program using switch statements that will assign letter grades based on if the user enters numbers 0 - 10. If the user enters a number that is not 0-10, the program outputs an error message and has the user re-enter. However, if the user enters a character the program will loop at the default case. I want it to output the error message from the default case once, and have them re-enter if they enter a character. I'm not sure as to why it loops the default case when a character is entered though.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
}
}
return 0;
}
Try something like:
#include <stdio.h>
int main()
{
int grade;
int r=0;
while(r != 1)
{
scanf("%i", &grade);
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
r=1
break;
case 8:
printf("Your grade is a B\n");
r=1
break;
case 7:
printf("Your grade is a C\n");
r=1
break;
case 6:
printf("Your grade is a D\n");
r=1
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
r=1
break;
default:
printf("Invalid score, please re-enter\n");
break;
}
}
return 0;
}
This will clear the input buffer on an invalid input and allow a retry.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
if ( r != 1) {//r == 1 is successful input of integer
grade = -1;//reset grade on invalid input
}
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
while ( getchar() != '\n');//clear input buffer
}
}
return 0;
}
The reason your code always loops is because there is no way to exit out of your while other than to kill the program. Remember that break only breaks out of the inner-most switch or loop.
The cleanest way to break out of multiple levels is to use a flag. One way to do what you want is like this:
bool valid_grade = false;
while(!valid_grade && (r = scanf("%i", &grade)) != EOF)
{
valid_grade = true;
switch(grade)
{
case 10:
// unchanged from your code
default:
valid_grade = false;
printf("Invalid score, please re-enter\n");
}
}
I have an assignment were I have to write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. I'm not able to use arrays or recursion, we're just starting with programming.
For example:
"123" returns "one two three"
My program is working well (for the most part), but the problem is that when you enter something like "0123" in the terminal the program returns "eight three"... WTH??
This is my code:
// Program that takes an integer and displays each digit in English
#include <stdio.h>
int main (void)
{
int num, digit;
int reversed = 0, backupZero = 0;
printf("Please enter an integer:\n");
scanf("%i", &num);
if (num == 0) // In case the input is just "0"
{
printf("zero");
}
while (num > 0) // Loop to reverse the integer
{
digit = num % 10;
reversed = (reversed * 10) + digit;
if ((reversed == 0) && (digit == 0)) // If the integer finishes in zero
{
++backupZero; // Use this to add extra zeroes later
}
num /= 10;
}
while (reversed > 0)
{
digit = reversed % 10;
reversed /= 10;
switch (digit)
{
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
default:
printf("zero ");
break;
}
}
for (int counter = 0; counter < backupZero; ++counter) // Prints the extra zeroes at the end
{
printf("zero ");
--backupZero;
}
printf("\n");
return 0;
}
Probably is something on the mathematics, I admit I'm not good at it.
When you read in the number with
scanf("%i", &num);
You are letting scanf infer the base of the number. Numbers starting with 0 followed by other digits are interpreted as octal. So 0123 is not the same as 123. It is in fact, 83.
0100 = 64
020 = 16
03 = 3
---------
0123 = 83
To read the number as base 10, use
scanf("%d", &num);
If you want to handle numbers that start with '0', then I suggest that you read the user input as a string (array of characters) rather than as an integer.
In addition to that, instead of "doing a switch" on each character, you can use a simple array in order to map the correct word to each digit.
Here is one way for implementing it:
#include <stdio.h>
#define MAX_INPUT_LEN 100
const char* digits[] = {"zero","one","two" ,"three","four",
"five","six","seven","eight","nine"};
int main()
{
int i;
char format[10];
char str[MAX_INPUT_LEN+1];
sprintf(format,"%c%us",'%',MAX_INPUT_LEN); // now format = "%100s"
scanf(format,str); // will write into str at most 100 characters
for (i=0; str[i]!=0; i++)
{
if ('0' <= str[i] && str[i] <= '9')
printf("%s ",digits[str[i]-'0']);
else
printf("invalid character ");
}
return 0;
}
Oh, wow. It took me 3 or 4 hours to write following code. I'm into c only first week, so please be considerate.
Update: added working minus + some comments.
#include <stdio.h>
#include <math.h>
int main(void)
{
int num, count, user, out;
count = 0;
printf("Type in any int: ");
scanf("%d", &num);
// adding minus to the beginning if int is negative
if (num < 0)
{
num = -num;
printf("minus ");
}
user = num;
// creating a power to the future number
while (num != 0)
{
num = num / 10;
count++;
}
int i2;
i2 = count;
// main calculations: dividing by (10 to the power of counter) and subtracting from the initial number
for (int i = 0; i < i2; i++)
{
out = user / pow(10, count - 1);
user = user - out * pow(10, count - 1);
count--;
switch (out)
{
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
case 0:
printf("zero ");
break;
default:
break;
}
}
printf("\n");
return 0;
}
There are some mistakes:
if ((reversed == 0) && (digit == 0)) (incorrect)
if ((reversed == 0) || (digit == 0)) (correct)
And in the last loop you should remove
--backupZero;
And code will read numbers better
So my professor asked us to create a switch statement. We are allowed to use only the "SWITCH" statement to do the program. He wants us to input a number and then display it if it is on the number range and what briefcase number will be taken as shown below. Now... I know that for this type of program it is easier to use the IF statement. Doing Case 1: Case 2: Case 3...Case 30 will work but will take too much time due to the number range.
#include <stdio.h>
main()
{
int x;
char ch1;
printf("Enter a number: ");
scanf("%d",&x);
switch(x)
{
case 1://for the first case #1-30
case 30:
printf("The number you entered is >= 1 and <= 30");
printf("\nTake Briefcase Number 1");
break;
case 31://for the second case #31-59
case 59:
printf("The number you entered is >= 31 and <= 59");
printf("\nTake Briefcase Number 2");
break;
case 60://for the third case #60-89
case 89:
printf("The number you entered is >= 60 and <= 89");
printf("\nTake Briefcase Number 3");
break;
case 90://for the fourth case #90-100
case 100:
printf("The number you entered is >= 90 and <= 100");
printf("\nTake Briefcase Number 4");
break;
default:
printf("Not in the number range");
break;
}
getch();
}
My professor told us that there is a shorter way on how to do this but won't tell us how. The only way I can think of shortening it is by using IF but we are not allowed to. Any Ideas on how I can make this work out?
With GCC and Clang, you can use case ranges, like this:
switch (x){
case 1 ... 30:
printf ("The number you entered is >= 1 and <= 30\n");
break;
}
The only cross-compiler solution is to use case statements like this:
switch (x){
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
printf ("The number you entered is >= 1 and <= 6\n");
break;
}
Edit: Using something to the effect of switch (x / 10) is another good way of doing this. It may be simpler to use GCC case ranges when the ranges aren't differences of 10, but on the other hand your professor might not take a GCC extension as an answer.
If the ranges are consistent, then you can throw away some of the data:
switch (x / 10 )
{
case 0:
case 1:
case 2: // x is 0 - 29
break ;
// etc ...
}
Otherwise you'll have to do a little bit of hackery around the edges.
Try this ...
#include <stdio.h>
main()
{
int x;
char ch1;
printf("Enter a number: ");
scanf("%d",&x);
int y=ceil(x/30.0);
switch(y)
{
case 1:
printf("The number you entered is >= 1 and <= 30");
printf("\nTake Briefcase Number 1");
break;
case 2:
printf("The number you entered is >= 31 and <= 60");
printf("\nTake Briefcase Number 2");
break;
case 3:
printf("The number you entered is >= 61 and <= 90");
printf("\nTake Briefcase Number 3");
break;
case 4:
printf("The number you entered is >= 91 and <= 100");
printf("\nTake Briefcase Number 4");
break;
default:
printf("Not in the number range");
break;
}
getch();
}
What I am trying to do is to write a program wherein you input two digits and
then they are converted into words which gets printed. The problem is that this program
hangs after you input the two digits and I have no idea why. Any and all help is appreciated.
I am a beginner and all I can use to solve this is basically if and switch. Thanks again.
#include <stdio.h>
int main (void)
{
int firstNum, secondNum;
printf("Enter a two digit number: ");
scanf("%d%d", &firstNum,&secondNum);
if (firstNum == 1 && secondNum == 0){
printf("You entered the number ten\n");}
if (firstNum == 1 && secondNum == 1){
printf("You entered the number eleven\n");}
if (firstNum == 1 && secondNum == 2){
printf("You entered the number twelve\n");}
if (firstNum == 1 && secondNum == 3){
printf("You entered the number thirteen\n");}
if (firstNum == 1 && secondNum == 4){
printf("You entered the number forteen\n");}
if (firstNum == 1 && secondNum == 5){
printf("You entered the number fifteen\n");}
if (firstNum == 1 && secondNum == 6){
printf("You entered the number sixteen\n");}
if (firstNum == 1 && secondNum == 7){
printf("You entered the number seventeen\n");}
if (firstNum == 1 && secondNum == 8){
printf("You entered the number eighteen\n");}
if (firstNum == 1 && secondNum == 9){
printf("You entered the number nineteen\n");}
switch(firstNum){
case 2: printf("You entered the number twenty-");break;
case 3: printf("You entered the number thirty-");break;
case 4: printf("You entered the number forty-");break;
case 5: printf("You entered the number fifty-");break;
case 6: printf("You entered the number sixty-");break;
case 7: printf("You entered the number seventy-");break;
case 8: printf("You entered the number eighty-");break;
case 9: printf("You entered the number ninty-");break;
}
switch (secondNum){
case 1: printf("one.\n");break;
case 2: printf("two.\n");break;
case 3: printf("three.\n");break;
case 4: printf("four.\n");break;
case 5: printf("five.\n");break;
case 6: printf("six.\n");break;
}
return 0;
}
Your program "hangs" because it is waiting for a second number.
Instead of 42ENTER, type 42fooENTER.
You need to verify the return value from scanf()
if (scanf("%d%d", &firstNum, &secondNum) != 2) {
fprintf(stderr, "Oops, the scanf didn't read 2 numbers.\n");
} else {
/* continue with program */
/* you might as well see what scanf got from the input */
printf("scanf got the values %d and %d.\n", firstNum, secondNum);
}
A very simple code (Specially for beginners).
#include <stdio.h>
#include <conio.h>
int main()
{
int num,n,r;
printf("Enter a two-digit number: ");
scanf("%d",&num);
n = num/10;
r = num%10;
switch(n)
{
case 1: switch(r)
{
case 0: printf("Ten");
break;
case 1: printf("Eleven");
break;
case 2: printf("Twelve");
break;
case 3: printf("Thirteen");
break;
case 4: printf("Fourteen");
break;
case 5: printf("Fifteen");
break;
case 6: printf("Sixteen");
break;
case 7: printf("Seventeen");
break;
case 8: printf("Eighteen");
break;
case 9: printf("Nineteen");
}
break;
case 2: printf("Twenty-");
break;
case 3: printf("Thirty-");
break;
case 4: printf("Fourty-");
break;
case 5: printf("Fifty-");
break;
case 6: printf("Sixty-");
break;
case 7: printf("Seventy-");
break;
case 8: printf("Eighty-");
break;
case 9: printf("Ninety-");
break;
}
if(n != 1)
{
switch(r)
{
case 1: printf("one");
break;
case 2: printf("two");
break;
case 3: printf("three");
break;
case 4: printf("four");
break;
case 5: printf("five");
break;
case 6: printf("six");
break;
case 7: printf("seven");
break;
case 8: printf("eight");
break;
case 9: printf("nine");
break;
default: ;
}
}
getch();
}
Your program reads data from the console and the console is in "cooked" mode. In this mode, the console collects the input and allows the user to edit it. Data is sent to the program after you press Return or Enter.
The mode you want is "raw" mode. There are various ways to enter raw mode but that depends on your OS.
The quick fix is to enter the two digits and press Return