#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if( 1<=n<=9)
{
switch(n)
{
case 1:cout<<"one"; break;
case 2:cout<<"two"; break;
case 3:cout<<"three"; break;
case 4:cout<<"four" ;break;
case 5:cout<<"five" ;break;
case 6:cout<<"six" ;break;
case 7:cout<<"seven"; break;
case 8:cout<<"eight" ;break;
case 9:cout <<"nine";
}
}
else
{ cout<<"greater than nine"; }
}
the above code when i am running (or)compiling my else statement is not working
for example if i am giving a number like 44 it is not displaying the statement in else that it is grater than nine but the if case is working nicely.
You have a problem with your if condition.
It should be like this:
if (n >= 1 && n <= 9)
As it is now, it means
if ((1 <= n) <= 9)
Which will always evaluate to true.
Try changing the condition to
if (1<=n && n<=9)
Related
Here, I've made a function, that takes a character array and a single element array as input.
The input of expression is like "56+78", and then someone suggested this approach of using ascii code and for loops to store the two "numeric" substrings as two numbers, and used the character and switch statement below. But, I don't understand the part of storing these substrings as numbers and the asciicode concept.
void calculate(char ch[], char op[]){
int i;
int num1 = 0, num2 = 0;
for(i=0; ch[i]!='\0';i++)
{
if((int)ch[i]>=48 && (int)ch[i]<=57){
num1 = num1*10+(((int)ch[i])-48);
}
else{
op[0]=ch[i];
break;
}}
i++;
for(; ch[i]!='\0';i++)
{
if((int)ch[i] >= 48 && (int)ch[i] <= 57){
num2 = num2*10+(((int)ch[i])-48);
}
}
cout<<"OUTPUT: ";
switch(op[0])
{
case '+':
cout<<num1 + num2<<endl;
break;
case '-':
cout<<num1 - num2<<endl;
break;
case '*':
cout<<num1 * num2<<endl;
break;
case '/':
cout<<num1 / num2<<endl;
break;
}
}
I was solving the a question at HackerRank -
Question Link - https://www.hackerrank.com/challenges/maximum-element/problem
In one solution I used 'break' statement in switch-case, in another solution I didn't.
Solution was wrong when I didn't use break statement. What is the reason behind this ?
Input -
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
With break Statement -
#include <bits/stdc++.h>
using namespace std;
int main() {
int noOfTestCases;
cin>>noOfTestCases;
vector <int> st;
for(int x=0; x<noOfTestCases; x++){
int query;
cin>>query;
switch (query) {
case 1:
int number;
cin>>number;
if(st.empty()){
st.push_back(number);
}
else if(number > st[st.size()-1]){
st.push_back(number);
}
else{
st.push_back(st[st.size()-1]);
}
break;
case 2:
if(!st.empty()){
st.pop_back();
}
break;
case 3:
cout<<st[st.size()-1]<<endl;
}
}
}
//Output -
//26
//91
Without break statement -
#include <bits/stdc++.h>
using namespace std;
int main() {
int noOfTestCases;
cin>>noOfTestCases;
vector <int> st;
for(int x=0; x<noOfTestCases; x++){
int query;
cin>>query;
switch (query) {
case 1:
int number;
cin>>number;
if(st.empty()){
st.push_back(number);
}
else if(number > st[st.size()-1]){
st.push_back(number);
}
else{
st.push_back(st[st.size()-1]);
}
case 2:
if(!st.empty()){
st.pop_back();
}
case 3:
cout<<st[st.size()-1]<<" "<<query<<endl;
}
}
}
//Output -
//0
//0
//0
//0
//0
//0
//0
//0
//0
//0
Consider the following code
switch (x) {
case 1:
std::cout << "one\n";
case 2:
std::cout << "two\n";
break;
case 3:
std::cout << "three\n";
}
If x is 1 it will print both one and two. It will then exit the switch block due to the break statement. Note that x will not be compared with 2 after printing "one", it will directly fall-through to printing "two".
So I had a misconception about switch case statement -
What I thought -
I thought that in switch case if the expression is equal to any case D, then further cases - E, F, G, will not be executed, irrespective of the break statement.
Reality - If an expression is equal to any case D, then further cases - E, F, G will also be executed if we don't use break statement.
Thanks Jeffrey and Paul Sanders to clarify this problem.
I wrote a simple function as the following, but it does not work as expected, in C++, the if statement doesn't work in the block of switch?
void any2ten(string origin, int type)
{
if(! (type == 2 || type == 8 || type == 16))
{
cout << "unsupport this " << endl;
return;
}
int result = 0;
for (int index = 0; index < origin.length(); index++)
{
int tmp = 0;
switch (origin[index])
{
if (type == 16)
{
case 'F':
case 'f':
tmp = 15 * pow(type, index); break;
case 'E':
case 'e':
tmp = 14 * pow(type, index); break;
case 'D':
case 'd':
tmp = 13 * pow(type, index); break;
case 'C':
case 'c':
tmp = 12 * pow(type, index); break;
case 'B':
case 'b':
tmp = 11 * pow(type, index); break;
case 'A':
case 'a':
tmp = 10 * pow(type, index); break;
case '9':
tmp = 9 * pow(type, index); break;
case '8':
tmp = 8 * pow(type, index); break;
}
if (type == 8 || type == 16)
{
case '7':
tmp = 7 * pow(type, index); break;
case '6':
tmp = 6 * pow(type, index); break;
case '5':
tmp = 5 * pow(type, index); break;
case '4':
tmp = 4 * pow(type, index); break;
case '3':
tmp = 3 * pow(type, index); break;
case '2':
tmp = 2 * pow(type, index); break;
}
case '1':
tmp = 1 * pow(type, index); break;
case '0':
tmp = 0; break;
default:
cout << "wrong character has got" << endl;
return;
break;
}
result += tmp;
}
cout << result << endl;
}
while I test the function as any2ten("aa", 8), the result is 90 rather than wrong character.
is there anything wrong?
The if statement works fine in the block of a switch, you've just put it in a place where it never gets executed. The switch statement jumps to the corresponding case, that is its purpose. Whatever it jumps to, it will skip over the if, so the if never executes.
If you were to add code to make it possible to jump to between the switch and the if, then the if would execute normally. You could do this with a loop of any kind or a goto.
A default is only taken if no case is matched. Otherwise, the switch jumps to the matching case.
The switch statement doesn't work the way you imagine that it works. The way it behaves is not as a substitute of an if-else if-else, but somewhat differently.
Upon encountering the switch the process will jump to the code following the correct case. This means that you actually completely skip the execution of the if that you have placed there.
And yes, it does look weird, since you assume that because you have the curly braces you must execute if condition or not enter into them at all, but this is simply not the case.
Well the placement of your if-statement doesn't really make sense. The switch-statement jumps to the corresponding case and then exists, hence your if-statement won't be executed. And I wouldn't recommend to use goto, cause it's considered as a bad-practice.
So when I put the limits of the integer that the switch case uses I keep getting a infinite number of the output of default for example:
int (num);
cout<<"Choose a number between 1-5"<<endl;
cin>>num;
while (num<1 || num>5)
{
switch (num)
{
case 1:
cout<<" Good"<<endl;
break;
case 2 :
cout<<" Okay"<<endl;
break;
case 3:
cout<<" Decent"<<endl;
break;
case 4:
cout<<" Nice Try"<<endl;
break;
case 5:
cout<<"Failed"<<endl;
break;
default
cout<<" Not Valid"<<endl;
break;
{
{
So for this example how would I make the user choose from 1-5 and if not repeat the loop in order for them to try again.
This will loop until valid number is given then test it in the switch case.
int num;
cout<<"Choose a number between 1-5"<<endl;
while(cin>>num && (num < 1 || num > 5));
switch (num)
{
... //for brevity
}
This will loop through the switch cases until a valid input is given.
int num;
bool keepLooping = true;
cout<<"Choose a number between 1-5"<<endl;
while(cin>>num && keepLooping)
{
keepLooping = false;
switch(num)
{
... //for brevity
default:
keepLooping = true;
}
}
So i need to have my switch statement go through and write out five two if the user says 52 but i cannot get it pass my 0-9. if they type 0-9 it works perfect but if i try to do any number past that it makes a blank. help!
#include <stdio.h>
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
for(x;x<0;x++);
switch (x)
{
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;
}
printf("\n\n");
return 0;
}
do {
switch (x%10) {
...
}
x = x / 10;
} while (x>0) ;
or to get it in the right order use recursion
void f(int x) {
if (x==0) return;
f(x/10);
switch(x%10) { ... }
}
This question has been asked-and-answered before.
The for-loop you wrote is empty, because the body of the loop ends with the semi-colon:
for(x;x<0;x++) /* Empty Body!!*/ ;
The way a typical for loop works is:
for( /*Initialize*/; /*Test*/; /*Change*/)
{
/* Body */
}
In your case, I think you want:
for(int i=0; i < x; ++i)
{
switch(x)
{
[...]
}
}
This will:
Initialize i to 0
Test if i is LESS THAN x (the number you entered)
Keep increasing i by 1, until it gets up to x.
I'm not going to do your homework for you but consider the following pseudo-code:
print_text_digits(x)
{
if (x >= 10) print_text_digits(x / 10);
switch (x) {
print "zero" through "nine" as appropriate
}
}
main()
{
scan number into x;
print_text_digits(x);
}
This relies on a recursive routine so that you get your digits processed one at a time, with the might significant digit printed first.
You could solve this with recursion.
void printDigit(int x) {
int digit = x%10;
if(digit!=x)
printDigit(x/10);
switch(digit) {
...
}
}
This will print the most significant figure first, unlike the while loops most people are mentioning.
I believe you need this:
#include <stdio.h>
int main (void)
{
int count = 0;
int x, count2;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
int aux = x;
while(aux>0) {
aux=aux/10;
count++;
}
count2 = count;
while(count) {
aux = x;
for(int i=count-1;i>0;i--)
aux=aux/10;
for(int i=count2-count;i>0;i--)
aux%=10;
switch (aux) {
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;
}
count--;
if(count) printf(" ");
}
printf("\n\n");
return 0;
}
Now, with an input 52 it will propelly return five two.
#include <stdio.h>
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
void printNum(int x)
{
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
printNum(x);
return 0;
}
Here's what you need to do. Similar to what #simonc said, it's a good idea to convert the user input to a string, then loop through the characters. For each character, convert it into an int and then take that into the switch statement.
EDIT---------------------------
Here's a way with strictly using integers.
First find how many digits your integer has. You can do this by a method mentioned here.
Then do integer division starting from the largest power of 10 that divides the integer you have and divide the divisor by 10 until you reach 1. For example:
If user input is 213, it has 3 digits. We divide this by 100 first.
213/100 = 2
We take the 2 and put it into the switch statement, outputting 2. Now we're done with the hundreds digit, so now we take the 13 from 213 and divide it by 10.
13/10 = 1 So now we output one.
Keep doing this process until you get to the ones digit.
Does this make sense?