Switch: Declared Variable outside switch and use it in it - c

The following isn't the it's just the part causing problem:
int s,p;
scanf("%d",s);
switch(s)
{
case 1:
{
p=10;
break;
}
case 2:
{
p=15;
break;
}
}
printf("%d",p);
The problem is that p prints a random and very large number, What is causing it?
So i used some of your advice and know i have the following code:
int s,p=0;
scanf("%d",&s);
switch(s)
{
case 1:
{
p=10;
break;
}
case 2:
{
p=15;
break;
}
default:
{
printf("Number invalid");
return 0;
}
}
printf("%d",p);
Now i it's always going to default even though i only enter 1 or 2
Ok now it worked Thank You All!

You have two problems: (i) p is uninitialised and (ii) you're passing s to scanf where the address of s is required.
Change:
int s,p;
scanf("%d",s);
to:
int s, p = 0;
scanf("%d", &s);

"int p" declaration assigns p to an arbitrary value: whatever happened to be in memory. Now, if s doesn't equal 1 or 2, that value never changes, and that's what you see. What you can do is
add default: clause to your switch() and assign p to something meaningful there
declare p as "int p = 0;"

What number are you scanning in? You probably you don't have a switch case for that number, which means that p is uninitialized (and hence random). For example if you enter 3, there is no case statement for 3 and p will contain a random value. I would suggest that you detect invalid input with an default case where you assign a value of 0 to p.
default:
p = 0;
Corrected code:
int s,p;
scanf("%d", &s);
switch(s)
{
case 1:
{
p=10;
break;
}
case 2:
{
p=15;
break;
}
default:
{
p=0;
break;
}
}
printf("%d",p);
Edit: Fixed scanf problem per Paul R

You can use default and then try to figure out what was scanned in

Related

exited with non-zero status

I am new in programming and try to learn by own ,i have an error in my code,i don't understand it's a syntax error or i've done smth wrong.I used 3 equations with it's condition and made it in for isntruction,while,do-while,if-else,with switch.After i introduce variable a it show me an error "exited with non-zero status".
#include <stdio.h>
#include <math.h>
int main() {
float a,x,b;
float L;
int m;
printf("Enter variables a,x,b:");
scanf("%f%f%f,&a,&x,&b");
printf("For using for instruction (enter 1)");
printf("For using while instruction (enter 2)");
printf("For using do-while instruction (enter 3)");
printf("For using ef instruction (enter 4)");
scanf("%d,&m");
switch(m){
case 1:
for (x=0;x<1.2;x++)
{
L=2*cos(x-(3.14/6));
}
for (x=0;x>= 1.2 && x<=3.9;x++)
{
L=x*x/(a+cos(powf((x+b),3)));
}
for (x=0;x>3.9;x++)
{
L=fabs(x/2*a)+powf(sin(x+1),2);
}
break;
case 2:
while (x<1.2)
{
L=2*cos(x-(3.14/6));
}
while (x>= 1.2 && x<=3.9)
{
L=x*x/(a+cos(powf((x+b),3)));
}
while (x>3.9)
{
L=fabs(x/2*a)+powf(sin(x+1),2);
}
break;
case 3:
do
{
L=2*cos(x-(3.14/6));
}
while (x<1.2);
do
{
L=x*x/(a+cos(powf((x+b),3)));
}
while (x>= 1.2 && x<=3.9);
do
{
L=fabs(x/2*a)+powf(sin(x+1),2);
}
while (x>3.9);
break;
case 4:
if (x<1.2)
{
L=2*cos(x-(3.14/6));
}
else
{
printf("First statement is false");
}
if(x>= 1.2 && x<=3.9)
{
L=x*x/(a+cos(powf((x+b),3)));
}
else
{
printf("Second statement is false");
}
if(x>3.9)
{
L=fabs(x/2*a)+powf(sin(x+1),2);
}
else
{
printf("Third statement is false");
}
break;
default:
printf("\nNo right choices\n");
}
printf("Your answer is: L = %.3f,L");
}
Your problem is that your scanf arguments are not formatted correctly.
Instead of scanf("%f%f%f,&a,&x,&b"); use scanf("%f%f%f",&a,&x,&b);. Same in the second scanf.
The variables addresses are parameters, not part of the string.
When you call it, scanf finds the first %f but it doesn't have any address to put the value into. Or more accuratly, it finds the value it needs from garbage (read about the stack and dynamic number of arguments), because you didn't insert it.
scanf("%f%f%f,&a,&x,&b"); should be like this scanf("%f%f%f",&a,&x,&b);. Please correct where ever you used scanf. Your code is not taking input from user due to wrong syntax. I have compiled and tried it is runnig correctly. Please change scanf syntax every where.
scanf("%f%f%f,&a,&x,&b") to scanf("%f%f%f",&a,&x,&b)
scanf("%d,&m"); to scanf("%d",&m);
printf("Your answer is: L = %.3f,L"); to printf("Your answer is: L = %.3f",L);
You are missing the return 0; Statement at the end of the main function. Since c main function is int main ()

Array gets ints from assignments of other variables in main. How is it possible?

I'm getting crazy with C. I'm writing code for my battleship DOS app. I'm using a int matrix (10x10) to build the field, but a weird thing happens. When I assign a value to an other variable, some points in the field change their value.
I don't know how it's possible.
I use to fill the matrix with '1' (int value), so I print a char to simulate a "sea point" on the battleship field. Here's the problem: some unwanted ints appear on the field.
I removed all the functions from the game, leaving only "printfield". It still happens. Please help!
(i'm italian, i tried to translate the variables names to make things easier. i'm sorry if i did some english errors. I also added a lot of printfield functions to see how the field changes during the app execution)
Here the code: (note: changing, for example, the "pos_x" assignment, the unwanted values change)
#include <stdio.h>
int printfield(int camp[][9]);
int fill(int campo[][9]);
int main()
{
int continua;
int field1a[9][9];
fill(field1a);
printfield(field1a);
continua=0; //what do this assignment do?????
while(continua==0)
{
printfield(field1a);
system("pause");
int pos_x=7; //what do this assignment do?????
printfield(field1a);
int pos_y=3; //what do this assignment do?????
printfield(field1a);
system("pause");
}
printfield(field1a);
system("pause");
system("cls");
printfield(field1a);
system("pause");
}
int printfield(int camp[][9])
{
printf("\n\n\n");
printf(" ");
int word;
for(word=97;word<=106;word++)
{
printf("%c ", (char)word);
}
int q, r;
for(q=0;q<=9;q++)
{
for(r=0;r<=9;r++)
{
if(r==0)
{
printf("\n");
if(q!=9) //to print '10' (the row number) correctly spaced -see the different number of spaces I put into the next printf
{
printf("%d ", q+1); //printf with 2 space for numbers 1-9
}
else
{
printf("%d ", q+1); //printf with 1 space for number 10
}
}
switch(camp[r][q])
{
case 1:
printf("~ ");
break;
case 2:
printf("0 ");
break;
case 3:
printf("S ");
break;
case 4:
printf("- ");
break;
case 5:
printf("X ");
break;
case 6:
printf("S ");
break;
case 7:
printf("- ");
break;
case 8:
printf("X ");
break;
default:
printf("E ");
break;
}
}
}
}
int fill(int campo[][9])
{
int f, h;
for(h=0;h<=9;h++)
{
for(f=0;f<=9;f++)
{
campo[f][h]=1;
}
}
}
You are trying to assign in a matrix[9][9] a number in a position [10].Remember a int [10] represents an array who starts at 0 until 9.
So, an array [9] starts at 0 to 8.
So you should or correct the matrix to be an matrix[10][10] or correct the for statement like that:
`for(q=0;q<9;q++)` (LESS **not** LESS EQUAL)
I hope I've helped you. I am not a native and my english is not good also.

Inside Switch Case - Variable Definition Related

In this code, why I am getting i = "some garbage value" as output? I see that i is being declared but value = 10, not assigned. Why ?
main()
{
int a =1;
switch (a)
{
int b = 10;
case 1: printf ("b = %d \n", b);
break;
}
b is not being initialized. The assignment is outside of any case in the switch, so it picks whatever was in the stack at that point.
If you want a variable inside a case statement, the right way to do it is:
switch(a)
{
case 1:
{
int b=10; //start a new block scope
printf("b=%d",b);
}
break;
}

remembering the value of a counter

#include <stdio.h>
int main()
{
int input, counter,value;
int ABC[3];
counter = 0;
scanf("%d", &input);
switch (input)
{
case 1:
if (counter >=4)
{
printf("Error\n");
}
scanf("%d", &value);
ABC[counter]= value;
printf("ABC[%d] is %d \n", counter, ABC[counter]);
counter++;
main();
break;
case 2: //do anything
main();
break;
default:
printf("a is anything\n");
break;
}
return 0;
}
I want to put in array ABC every time i choose case 1 a value, until array ABC is full. My problem is, that i can only enter in this programm values into ABC[0] . Is there any way, to remember the value of counter, so it's not always 0? Maybe using if-statement? But how to formulate an if-statement in this programm, which is only once in the beginning true?
But ABC should also be allowed to have empty space
After "counter++" you are re-calling your "main" function, that reinitializes your counter to 0. You should use a loop:
int counter = 0;
do
{
// Your scanf goes here
switch(scanf_result)
{
// Add your case labels here
default: // Incorrect input? Let's start again!
continue;
};
counter++;
}
while(counter < 3);
i think that declaring counter outside the main function, would make it global scope.
in this way everytime you call main(); you reset the value to 0.
so write int counter = 0 before the main declaration, at row number 2.

Repetition using switch statement inside a for loop

I am trying to use a loop to print out a repetitive song, "this old man"
The first verse is:
This old man, he played one
He played knick-knack on my thumb
This old man came rolling home
This song repeats to ten, varying the two terms in italicize
one -> two++ and thumb -> another item such as shoe, knee, etc.
Here is my code so far:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
string change1 (int i);
int main (void)
{
for (int i = 1; ; 1 < 11; i++)
{
printf ("This old man, he played ");
change1(i);
printf("He played knick-knack on my %s\n\n", s1);
}
return 0;
}
string change1(int i)
{
string s1;
switch(i)
{
case 1:
{
printf("one\n");
s1 = "thumb";
}
break;
case 2:
{
printf("two\n");
s1 = "shoe";
}
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
printf("ill add these cases later");
}
}
This gives me an error message of: "control reaches end of non-void function"
I also got an undeclared variable s1 error but I declared it in the function.
You could simplify your program to an actual C program, rather than C++
int main (void)
{
int i;
char* items[] = {"thumb", "shoe", "", "", "", "", "", "", "", ""};
char* numbers[] = {"one", "two", "three","four","five","six","seven","eight","nine","ten"};
for (i = 0; i < 10; i++)
{
printf ("This old man, he played %s\n", numbers[i]);
printf("He played knick-knack on my %s\n\n", items[i]);
}
return 0
}
In C++ variables have scope. A variable is generally visible inside the curly braces where it is declared; outside these brackets the variable does not exist.
That is why you cannot use s1 from change1 inside the loop: you need to return a value (best choice in your situation), or use a variable that is in scope in both change1 and main.
printf ("This old man, he played ");
printf("He played knick-knack on my %s\n\n", change1(i));
...
string change1 (int i) {
string s1;
switch (i) {
...
}
return s1;
}
Note that you do not need a switch statement to implement change1: when the code is so uniform, you may be better off with an array:
const char *strings[] = {"thumb", "shoe", ...};
change1 needs to return the string it decided on. And main has to assign the return value to a variable, because as originally written s1 is local to the change1 function.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
string change1 (int i);
int main (void)
{
for (int i = 1; ; 1 < 11; i++)
{
printf ("This old man, he played ");
string s1 = change1(i);
printf("He played knick-knack on my %s\n\n", s1);
}
return 0;
}
string change1 (int i)
{
string s1;
switch (i)
{
case 1:
{
printf("one\n");
s1 = "thumb";
}
break;
case 2:
{
printf("two\n");
s1 = "shoe";
}
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
printf("ill add these cases later");
}
return s1;
}
use return statement at the end of switch class
return s1;

Resources