C case-switch statement not running through full loop - c

Trying to solve a problem on kattis.com called "Bela", which requires some character comparison, but when i run my code the scanf() function does not get called the last couples time for the last couple iterations of the loop.
here is my code:
#include <stdio.h>
int main( void ) {`
char dom;
int n;
scanf("%d %c", &n, &dom);
n*=4;
int sum = 0;
for (int i = 0; i < n; i++) {
char num;
char suit;
scanf("%c%c", &num, &suit);
switch (num) {
case 'A':
sum += 11;
break;
case 'K':
sum += 4;
break;
case 'Q':
sum += 3;
break;
case 'J':
if (suit == dom) { sum +=20;}
else { sum += 2;}
break;
case 'T':
sum+=10;
break;
case '9':
if (suit == dom){sum+=14;}
break;
case '8':
break;
case '7':
break;
default:
continue;
}
}
printf("%d", sum);
return 0;
}
and when i run the with this test case program i get this:
:~$ ./a.out
^V
2 S
TH
9C
KS
QS
JS
TD3
AD
JH
:~$ TD
TD: command not found
:~$ AD
AD: command not found
:~$ JH
JH: command not found
why is the for loop not executing completely? Is there anyhting inherently wrong with my code that the switch case statement does not evaluate "TD", "AD", "JH"?

why is the for loop not executing completely?
Add printf("\nEnter:"); before second scanf check it. The loop execute fully but the scanf catches spaces.
So,
Add
while((ch=getchar()!='\n')&&ch!=EOF);
Before the second scanf or change second scanf to
scanf(" %c%c", &num, &suit);
^
This statements are ignore spaces(' ','\n',...)

Related

How can we update the value of a global variable using switch statement in C?

int mmak = 0;
int main(void)
{
int marks[3] [3] = {{0,5,6}, {1,5,9}, {2,9,5}};
for (int k = 0; k < 3; k++)
{
int sunk = marks[k] [0];
switch (sunk)
{
case '0': mmak++;
break;
case '1': mmak++;
break;
case '2': mmak++;
break;
}
}
printf("%i\n", mmak);
}
I want to update the value of global variable mmak. but the output I am still geting is 0. Can anyone help?
Even if the issue is solved by removing single quoting of the clauses of your switch, I'd like to enrich this by adding some remarks:
You should always consider a default case in a switch statement that covers unexpected situations.
When you are printing an int you should use '%d' instead of '%i' for the reason explained here: ...difference between %d and %i ....
Always end your main with a return [int]; statement.
#include <stdio.h>
int mmak = 0;
int main(void)
{
int marks[3] [3] = {{0,5,6}, {1,5,9}, {2,9,5}};
int sunk;
for (int k = 0; k < 3; k++)
{
sunk = marks[k] [0];
switch (sunk)
{
case 0:
mmak++;
break;
case 1:
mmak++;
break;
case 2:
mmak++;
break;
default:
printf("No value found\n");
break;
}
}
printf("%d\n", mmak);
return 0;
}
case '2':
This case compares to the ASCII '2' (int 50), which is not the same as int 2. Instead use:
case 2:
The additional advice from comments for falling through cases will help when the same operation will be performed for more than one case:
case 0:
case 1:
case 2: mmak++;
break;
case 3: mmak+=2;

Why does my program skip a switch instruction?

I am trying to write a program, where after 7 floats inputted by the user; they get stored into an array, then get printed out like this:
DAY VALUE ISTOGRAM
1 37.8 ***
2 40.6 ******
where the number of * in the Istogram column is given by value - 34.
I've written this code:
#include <stdio.h>
#define OBSERVATION 7
#define MEDIAN 34
int main() {
float temp[OBSERVATION] = {0};
printf("Insert the patient's temperature over the course of 7 days: ");
for(int i = 1; i <= OBSERVATION; i++){
scanf("%f", &temp[i]);
}
printf("DAY\tVALUE\tISTOGRAM\n");
for(int i = 1; i <= OBSERVATION; i++){
printf("%6d\t%6g\n", i, temp[i]);
}
for(int i = 1; i <= OBSERVATION; i++){
switch ((int)temp[i] - MEDIAN) {
case 0: break;
case 1: printf("\t\t\t\t*");
break;
case 2: printf("\t\t\t\t**");
break;
case 3: printf("\t\t\t\t***");
break;
case 4: printf("\t\t\t\t****");
break;
case 5: printf("\t\t\t\t*****");
break;
case 6: printf("\t\t\t\t******");
break;
case 7: printf("\t\t\t\t*******");
break;
case 8: printf("\t\t\t\t********");
break;
case 9: printf("\t\t\t\t*********");
break;
case 10: printf("\t\t\t\t*********");
break;
case 11: printf("\t\t\t\t**********");
break;
case 12: printf("\t\t\t\t***********");
break;
}
printf("\n");
}
return 0;
}
The code compiles fine and outputs the first two columns correctly, but completely skips the switch statement. I've already tried to check if it erroneously assigns 0 to temp[i] when it gets cast to an int, but it doesn't do that. It simply skips the switch.
Also do you have a more "compact" way on how to print out the * column without using a switch?
I would rewrite your code like this:
#include <stdio.h>
#include "math.h"
#define OBSERVATION 7
#define MEDIAN 34
int main() {
float temp[OBSERVATION] = {0};
int iDifference = 0;
printf("Insert the patient's temperature over the course of 7 days: \n");
for(int i = 0; i < OBSERVATION; i++){
scanf("%f", &temp[i]);
}
then print the headers:
printf("DAY\tVALUE\tISTOGRAM\n");
start the row loop:
for(int i = 0; i < OBSERVATION; i++){
// calculate the difference integer
iDifference = round(temp[i] - MEDIAN);
// don't add stars if the temperature diff is lower than 0
if(iDifference < 0) iDifference = 0;
// print the first two columns, notice that the new line isn't added yet
printf("%6d\t%6.2f\t", i, temp[i]);
// print the stars
vDrawStars(iDifference);
// then write the newline character
printf("\n");
}
return 0;
}
then the drawing stars routine:
void vDrawStars(int prm_iCount){
int p = 0;
// I didn't understand the case for it but
// printf("\t\t\t\t");
// then draw the needed stars
for(p = 0; p < prm_iCount; p++)
{
printf("*");
}
// no new lines, still on the same line.
}
Here's a demo here: https://onlinegdb.com/BJPyvDJRX
Your code works incorrectly, because you access the array temp out of bounds. Array indexes start with zero, so you should index with for(int i = 0; i < OBSERVATION; i++).
The switch:
switch ((int)temp[i] - MEDIAN) {
case 0: break;
case 1: printf("\t\t\t\t*");
break;
case 2: printf("\t\t\t\t**");
break;
case 3: printf("\t\t\t\t***");
break;
case 4: printf("\t\t\t\t****");
break;
case 5: printf("\t\t\t\t*****");
break;
case 6: printf("\t\t\t\t******");
break;
case 7: printf("\t\t\t\t*******");
break;
case 8: printf("\t\t\t\t********");
break;
case 9: printf("\t\t\t\t*********");
break;
case 10: printf("\t\t\t\t*********");
break;
case 11: printf("\t\t\t\t**********");
break;
case 12: printf("\t\t\t\t***********");
break;
}
may be optimized just to:
const int val = (int)temp[i] - MEDIAN;
if (1 <= val && val <= 12) { // make sure it's between 1 and 12
printf("\t\t\t\t%.*s", val, "***********");
}
The printf format modifier "%.*s" takes two parameters - length of the string to print and the string itself
We print val length of "**********" characters.

How do I get switch() to loop multiple times in C?

I have created this fruit machine game. However I would like to loop the output several times before printing a final output that is then scored. To simulate the moving nature of a real slot machine. When I try and loop my switch() statements no output is produced. How would I go about doing this?
#include <stdio.h>
#include <unistd.h>
int main ()
{
int firstReel, secondReel, thirdReel, loop;
// Generating three random numbers
srand(time(NULL));
int rndOne = rand () %4;
int rndTwo = rand () %4;
int rndThree = rand () %4;
// Assigning random numbers to clearer var names
firstReel = rndOne;
secondReel = rndTwo;
thirdReel = rndThree;
// Switch statements for each reel
switch(firstReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
switch(secondReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
switch(thirdReel){
case 0:
printf("Bell\n");
break;
case 1:
printf("Cherry\n");
break;
case 2:
printf("Orange\n");
break;
case 3:
printf("Horseshoe\n");
break;
}
// Win/lose conditions
if (firstReel == secondReel || firstReel == thirdReel || secondReel == thirdReel)
printf("Congratulations! You win!\n");
else
{
printf("Sorry, you lose. Play again? (Y/N)\n");
}
}
use some sort of counter/ looping statement
int i=0;
while(i< 10){
//Your switch statements
i++;
}
As a better programming practice please do include default case/scenario too when the switch input doesn't satisfy any of the cases.. helps in keeping the code structured and avoids any confusion also showing that other values have been taken care of. For ex:
default:
printf("Invalid value entered");
break;
Try using a loop as shown below :
Here I am running the loop for some x number of times.You can run the loop for any number of times you wish to.
int main ()
{
int firstReel;
int i=0;
// Generating three random numbers
srand(time(NULL));
// Assigning random numbers to clearer var names
while(i<7)
{
firstReel = rand () %4;
// Switch statements for each reel
switch(firstReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
i++;
}
}
This will show the reels spinning and slowing to the final pattern (in a console).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SYMBOLS 4
#define REELS 3
#define SPINS 20
char *symbol [SYMBOLS] = {" Bell ", " Cherry ", " Orange ", "Horseshoe "};
int reel [REELS];
int main(int argc, char **argv)
{
int s, r, elap, tix, counts;
srand ((unsigned)time(NULL));
for (s=SPINS; s>0; s--) {
printf ("\r");
for (r=0; r<REELS; r++) {
reel [r] = rand() % SYMBOLS;
printf ("%s", symbol [reel [r]]);
}
tix = clock();
counts = CLOCKS_PER_SEC / s;
do {
elap = clock() - tix;
}
while (elap < counts);
}
printf ("\n");
for (r=1; r<REELS; r++)
if (reel [r] != reel [r-1])
break;
if (r < REELS)
printf ("You lost!\n");
else
printf ("You won!\n");
return 0;
}

Counting number of vowels and consonants in a string

I keep on getting a [Linker error]C:\Users etc and collect2: Id returned 1 exit status code errors on my program but I don't see anything wrong with it. This is my program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main (){
int vowels = 0, cnsnts = 0;
int i, length;
char string[100];
printf("Enter sentence:");
gets(string);
length = strlen(string);
for(i = 0; i < length; i++){
switch(toUpper(string[i])){
case 'A':
vowels++;
break;
case 'E':
vowels++;
break;
case 'I':
vowels++;
break;
case 'O':
vowels++;
break;
case 'U':
vowels++;
break;
default:
cnsnts++;
}
}
printf("The number of vowels are %d.\n", vowels);
printf("The number of consonants are %d.\n", cnsnts);
system("pause");
return 0;
}
Change
toUpper(string[i])
to
toupper(string[i])
add <ctype.h> header and turn on your compiler warnings.
First add
#include <ctype.h>
then change the camel case toUpper like so
toupper(string[i])
You must #include <ctype.h> and have mistakenly capitalized the u in upper. Your switch could also stand to be brought down a bit
switch(toupper(string[i])) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
break;
default:
cnsnts++;
}
This style takes advantage of fall-throughs. If a case doesn't end with a break (or return, continue, or goto) it will enter the case below it. This continues until a control flow altering keyword is hit. The switch above is functionally equivalent to your original, but a lot shorter.
You might also consider checking that string[i] is a letter at all with isalpha before the switch
if (!isalpha(string[i])) continue;

Switch statement letter to integer

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'.

Resources