Simpe if and else in C programming - c

I want to make this program say that if you enter 1 the screen will display "yes G is the 1st note in a G chord", if you enter anything else it will print "wrong!" and then loop back into the beginning, here is my attempt at it. Also, I know there are different ways to do this, but it is for a school assignment and the enum data-type is necessary, though this code is far reaching for just displaying use of enum, it bothers me I can't get this to work. Any pointers? (no pun intended).
enum Gchord{G=1,B,D,};
int main(){
printf( "What interval is G in the G chord triad \nEnter 1 2 or 3\n" );
int note;
scanf("%i",&note);
if (note = 1 ){
printf ("Yes G is %ist note in the G-chord\n",G )};
else(
printf("no, wrong");
return(0):
};

note = 1 is assigning note with the value 1. You are looking to compare note with 1 and therefore you need the operator ==. Read up on comparison operations here:
http://en.cppreference.com/w/cpp/language/operator_comparison
To be crystal clear:
note = 1; // Assigning note to 1, note is now the value 1
note == 1; // Comparing note to 1, true if note is 1, false otherwise.
You also have plenty of other problems:
In printf ("Yes G is %ist note in the G-chord\n",G )}; Lines end with semicolons, if statements don't.
else( else doesnt take an argument and should use a curly brace. else {
return(0) Return is not a function.
Your compiler with warnings on full (-Wall) will tell you all of these things. Things in the list above should have been compiler errors.

There a lot of problems in your code, but the main one is because you try to assign 1 to note instead of the comparission ==.
Another thing is that you never check scanf for errors.
There are parentheses and brackets used wrong.
int main(){} shoudl be at least int main(void){}.
The return statement should be not treated as a function, there are no need of those parentheses around (0) and should end with a semicol ; and not with :.
Now the following should explain you better what you probably tried to do:
#include<stdio.h>
enum Gchord{G=1,B,D,};
int main(void){
printf( "What interval is G in the G chord triad \nEnter 1 2 or 3\n" );
int note;
if(scanf("%i",&note) == 1){
if (note == 1 ){
printf ("Yes G is %ist note in the G-chord\n",G );
}else{
printf("no, wrong");
}
}else{
printf("Error, scanf\n");
}
return 0;
}

I don't know where to start. Your code has a lot of errors.
Code formatting: it is very important to learn how to format your code so it becomes easier to read it.
int note; variables should almost always be declared at the top and also initialized (in this case with int note = 0;
If you separate something with , enter a space behind it. not scanf("%i",&note); but scanf("%i", &note);
To compare if 2 values are equal, use ==. A single = is used to assign values to a variable. Wrong: if (note = 1 ) Right: if (note == 1)
You are using a wrong bracket for the else that you do not even close.
And for your problem of looping, you should read up about while loops and ask again if you don't understand them.
enum Gchord{G=1,B,D,};
int main() {
int note = 0;
printf("What interval is G in the G chord triad \nEnter 1 2 or 3\n");
scanf("%i", &note);
if (note == 1) {
printf ("Yes G is %ist note in the G-chord\n", G);
}
else {
printf("no, wrong");
}
return 0;
};

There are a myriad of syntax errors in here including the one everyone has pointed out that note = 1 assigns a value of 1 to the note variable instead of testing for equality. You want the == operator here.
Also you aren't really using the enum, your teacher probably wont pass you on this.
I modified your code a bit to make a little more use of the enum and to do the loop you are looking for.
enum Gchord { EXIT, G, B, D, };
int main()
{
while (true)
{
printf("What interval is G in the G chord triad \nEnter 1, 2, 3, or 0 to exit\n");
Gchord note;
scanf("%i", &note);
if( note == EXIT )
break;
if (note == G)
printf("Yes G is %ist note in the G-chord\n", G);
else
printf("no, wrong\n");
}
return(0);
};

Related

Weird Error when using atof in c

I understand there are bugs with "Bad Input" but for some reason i cant even get good input to go through. It's either returning a value of 10 or 0 and i can't seem to find the reason why. Below is where i am calling it:
var1 is datatype float. All headers are included that are needed.
floatHolder is datatype char array.
Below is where i am calling it:
scanf("%s", &floatHolder);
var1 = inputchecker(floatHolder);
this is the function that is called:
float inputchecker(char *charArray)
{
float f = 0;
float f2 = 0;
int i = 0;
int z = 0;
int badInput = 0;
char errorArray[15];
func1:
while (i<strlen(charArray))
{
if (charArray[i]<48 || charArray[i]>57)
{
if (charArray[i] == 46)
{
i++;
goto func1;
}
printf("\n Entered value contains alphabets or symbols, please enter numerical/Floating point values only.\n");
printf("Re-enter Correct Input Please: ");
scanf("%s", &errorArray);
getchar();
badInput = 1;
goto func2;
}
i++;
}
func2:
while (z < strlen(errorArray) && badInput == 1)
{
if (errorArray[i] < 48 || errorArray[i]>57)
{
if (errorArray[i] == 46)
{
z++;
goto func2;
}
printf("Re-enter Correct Input Please: ");
scanf("%s", &errorArray);
getchar();
}
z++;
}
badInput = 0;
f = atof(charArray);
f2 = atof(errorArray);
if (f == 0)
{
return f2;
}
if (f2 == 0)
{
return f;
}
}
For some reason after the function is called it shows a correct return value ex. if i give it 4 it will return 4 but var1 will show a insanely large number, 0, and 10. If anyone can let me know what i'm doing wrong it would be greatly appreciate.
I tried out your routine and received similar results. Then I realized what you problem is. You probably neglected to put a function prototype at the top of your file.
float inputchecker(char *charArray);
By neglecting to use a prototype the compiler will have to guess the signature of the function and the stack may not be restored properly and your return value then will be corrupted.
When I added the prototype at the top of the file, everything worked fine for valid float inputs such as 3.14
Note: different versions of C will behave differently. For example C89/C90 will 'guess' what the parameters will be without a prototype. This can be quite dangerous and it is what I think happened in your situation. I think C99 works in a similar way but with some differences.
Another, proof that you are not using a prototype is that you are receiving integer answers. When the compiler 'guesses' the prototype, it will typically return an int. Furthermore, this also explains why you are getting the same results for different input, you are getting the contents of the same memory location (not your f variables) due to the stack corruption.
Its very very good practice to always define function protoypes at the top of your file.

Error when using array elements in conditional statements in C

I have done my fair share of studying the C language and came across this inconsistency for which I cannot account. I have searched everywhere and reviewed all data type definition and relational syntax, but it is beyond me.
From the book C How to Program, there is a question to make a binary to decimal converter where the input must be 5-digits. I developed the follow code to take in a number and, through division and remainder operations, split it into individual digits and assign each to an element in of an array. The trouble arises when I try to verify that the number entered was indeed binary by checking each array element to see whether it is a 1 or 0.
Here is the code:
#include <stdio.h>
int power (int x, int y); //prototype
int main(void)
{
int temp, bin[5], test;
int n=4, num=0;
//get input
printf("%s","Enter a 5-digit binary number: ");
scanf("%d", &temp);
//initialize array
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
//verify binary input
for (test=4; test>=0; test--){
if ((bin[n]!=0)&&(bin[n]!=1)){
printf("Error. Number entered is not binary.\n");
return 0; }
//convert to decimal
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
printf("\n%s%d\n","The decimal equivalent of the number you entered is ",num);
return 0;
}
//function definition
int power(int x, int y)
{
int n, temp=x;
if(y==0) return 1;
for(n=1; n<y; n++){
temp*=x; }
return temp;
}
Could someone explain to me why regardless of input (whether: 00000, or 12345), I always get the error message? Everything else seems to work fine.
Thank you for your help.
Update: If the if statement is moved to the while loop before. This should still work right?
Update2: Never mind, I noticed my mistake. Moving the if statement to the while repetition before does work given the solution supplied by sps and Kunal Tyagi.
After this
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
n is set as -1 so when you try to convert to decimal the statement bin[n] is actually bin[-1] so it returns you error.
One issue is that, while checking if the number is binary or not, you are returning at wrong place. You need to return only if the number is not binary. But you are returning outside the if condition. So your program returns no matter what the input is.
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1))
printf("Error, numbered entered was not binary.\n");
// Issue here, you are returning outside if
return 0; } //exit program
You can change that to:
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1)) {
printf("Error, numbered entered was not binary.\n");
// Return inside the if
return 0; // exit program
}
}
There is one more issue. Before you convert your number to decimal, you need to set n = 0;
//convert to decimal
n = 0; /* need to set n to zero, because by now
n will be -1.
And initially when n is -1, accessing
bin[-1] will result in undefined behavior
*/
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
This looks like a homework, but your issue is in the brackets. More specifically line 23. That line is not part of the logical if statement despite the indentation (since that doesn't matter in C).
No matter what, the program will exit on test=4 after checking the condition.
Solution:
if ((bin[test]!=0)&&(bin[test]!=1)) { // << this brace
printf("Error, number entered was not binary.\n");
return 0; } } //exit program // notice 2 braces here

Programming while loop in C

First, I am a total beginner, so the question is probably very obvious for all of you, but i don't get what's wrong with the while loop in this program. Te aim of the program is to calculate the average between numbers where the user inputs 0 when he wants to continue putting numbers in and inputs 1 when he wants to stop, so the loop is supposed to stop when the user puts 1 and to compute a sum of the values when he enters 0 at the end. So this is what i wrote, i used stdio.h and stdlib.h as libraries :
int decision;
int value;
int sum = 0;
float av;
int order = 1;
printf ("for continue press: 0\n ");
printf ("for stopping press: 1\n ");
while (decision == 0) {
printf("input value:");
scanf("%d", &value);
sum = sum + value;
printf ("continue?");
scanf("%d", &decision);
order = order + 1;
}
av = (float) sum / (float) order;
printf("the average is: %.2f", av);
return EXIT_SUCCESS;
what the terminal displays is just "the average is:0.00", it skips the whole operation above.
You should initialize decision to 0
int decision = 0;
so that the while loop is true
while (decision == 0) {
on the first iteration.
In C, simply declaring a variable does not assign it a value of 0. You have to do that. In fact, actually using a variable that has not been initialized is undefined behavior. Most likely, the variable contains whatever contents was in the memory location assigned to it.
The solution is to actually define decision.
int decision = 0;
In C, declaring a variable does not initialize it. So the initial value of decision is more or less random. If it's not zero (and it likely is not), the cycle is never entered.
Perversely, when in "debug mode" or using some instrumentation such as valgrind, memory might be either zeroed or initialized consistently, leading to "unreproducible" bugs that may be difficult to track. That is why you really want to always initialize your variables
Try with:
int decision = 0;
Also, turn on all compiler warning flags. You want to be warned when such things happen, and the compiler can do so if you tell it to.
Another way
You do not need decision anywhere else, so it's good to have one less variable in the outer scope:
for (;;) {
int decision; /* The variable only lives inside this loop */
printf("input value:");
scanf("%d", &value);
sum = sum + value;
printf ("continue?");
scanf("%d", &decision);
if (0 == decision) {
break;
}
order = order + 1;
}
Notice
If you start order from 1, and enter only one value, order will be increased to 2, and this will get your calculation off. Either start from 0 or increase the value after decision confirmation.
You have not initialized the decision variable and that is why the error.
int decision = 0;

if-else code for total price won't compile

what is wrong with this im to make c code for total price with one of three ram options.et ramchoices=1or2or3 /this is where I know my problem lies but don't know how to fix it. the compiler needs a one to one relationship. how do I break this up and still show that ramchoice depends on what I pick and those choices affect price./
int main(void) {
/*declare variables*/
float baseprice;
float total;
float ramchoice;
baseprice=1029.48;
/*ramchoice can be 1 or 2 or 3*/
ramchoice=1||ramchoice=2||ramchoice=3;
total=baseprice+ramchoice;
/*initiate variable*/
scanf("%f",&ramchoice);
if("%f" (ramchoice==1))
{
total=baseprice+179.99;
}
else if("%f" ramchoice==2)
{
total=baseprice+94.99;
}
else if("%f" ramchoice==3)
{
total=baseprice+69.99;
}
printf("total is %f",total);
return 0;
}
There are several lines that are unlike any C code I've ever seen before.
Are you completely making up your own syntax and meaning?
Have you read any instructions/tutorials on C?
ramchoice=1||ramchoice=2||ramchoice=3;
Whatever you think this line does, it sets variable ramchoice to have value 1, then it stops.
if("%f" (ramchoice==1))
if does NOT take a string like "%f". if expects a boolean expression.
You're close to a boolean with ramchoice==1, but the "%f" at the start is so very wrong.
Seriously, you cannot make up rules to a language and pray that it works.
Here is my re-write that pretty much fixes your issues:
int main(void)
{
/*declare variables*/
float baseprice = 1029.48;
float total;
int ramchoice;
printf("Please enter a ram selection: 1, 2, or 3\n");
scanf("%d",&ramchoice);
switch(ramchoice)
{
case 1: total=baseprice+179.99; break;
case 2: total=baseprice+94.99; break;
case 3: total=baseprice+69.99; break;
default: printf("That was not a valid choice\n");
}
printf("total is %f",total);
return 0;
}
There's somethings in your code that make no sence (are not correct in C):
ramchoice=1||ramchoice=2||ramchoice=3; total=baseprice+ramchoice;
"%f" (ramchoice==1)
The first I don't understand why you are using it.
The second one gives me the idea that your not understanding how scanf works.
Also, you are declaring ramchoice as a float, but you are comparing it to another value (1, 2 or 3). Due to the representation of float values, this may not work. I mean, if you have float x = 1; and then do x == 1, it may return false. To fix this you can just change it to an int (in this case, in others you can use an error margin).
Here's a fix of your code:
int main(void) {
/*declare variables*/
float baseprice;
float total;
int ramchoice;
baseprice=1029.48;
/*initiate variable*/
scanf("%i",&ramchoice);
if(ramchoice==1)
{
total=baseprice+179.99;
}
else if(ramchoice==2)
{
total=baseprice+94.99;
}
else if(ramchoice==3)
{
total=baseprice+69.99;
}
printf("total is %f",total);
return 0;
}
Get rid of the "%f" in the if statements
Comment those 2 lines:
ramchoice=1||ramchoice=2||ramchoice=3;
total=baseprice+ramchoice;
and code should compile.

Averaging 3 integers

My assignment is to fix the code. I have my edited code below and the original code below that. I figure I still have a few errors in here. My error checking doesnt seem to work, and I am not sure if my getchar() function is written or working properly.
Please assume I know nothing becasue that is fairly accurate.
The code compiles, but the answer is always 2. I am about 4 hours into this piece of code with 3 more to work after this.
My code
#include <stdio.h>
double get_number(double num);
main () {
double n1,n2,n3;
double average;
printf("\nCompute the average of 3 integers\n");
printf("--------------------------------\n");
n1 = get_number(1);
n2 = get_number(2);
n3 = get_number(3);
average = (n1 + n2 + n3)/3;
printf("The average is %0.2f\n",average);
}
double get_number(double num) {
double value = 0;
char c;
int i;
printf("Please input number %d: ", num);
while (c = getchar != '\n') {
if ( (c>9) || (c<0) ) {
printf("Incorrect character entered as a number - %c\n",c);
return(0);
}
else {
value = num;
}
}
return(value);
}
Original code
#include <stdio.h>
main () {
double n1,n2,n3;
double average;
printf("\nCompute the average of 3 integers\n");
printf("--------------------------------\n");
n1 = get_number(1);
n2 = get_number(2);
n3 = get_number(3);
average = (n1 + n2 + n3)/3;
printf("The average is %0.2f\n",average);
}
double get_number(int num) {
double value = 0;
char c;
printf("Please input number %d: ", num);
while (c = getchar() != '\n') {
if ( (c<=9) && (c>=0) ) {
printf("Incorrect character entered as a number - %c\n",c);
exit(-1);
}
else {
value = 10*value + c - '0';
}
}
return(value);
}
A few issues:
1. You should be using '9' and '0', since you want the ASCII values for digit '9' (0x39) and '0' (0x30), not 0x9 and 0x0.
if ( (c>'9') || (c<'0') ) {
2. != has higher precedence than =, so you need parens. Learn operator precedence, and if you're in doubt, use parens:
3. getchar is a function not a variable.
while ((c = getchar()) != '\n') {
4. You use the wrong conversion. num is a double, so you would need %f. Or, you could make num a int.
printf("Please input number %f: ", num);
5. You never actually use c in any way (except error checking). You always return 0 or num (see your else clause), which makes no sense. The else body of the original is correct.
You got the floating point parsing all wrong and shouldn't be doing it yourself. There's an easier way:
double get_number(double num) {
double value = 0.0;
printf("Please input number %lf: ", num);
scanf("%lf", &value);
return(value);
}
The issues with the original program are:
getchar() returns an ASCII code, and the condition was wrong. When checking for boundaries, use ((c<'0') || (c>'9')).
For the exit function you need to include "stdlib.h".
For the main function to understand what is get_number, you need to either move the function to be before the main function, or you can use a forward declaration.
The assignment operator (=) has lower precedence than the inequality operator (!=), so you need to use parenthesis, like: ((c = getchar()) != '\n')
You have actually created several more issues, so I wouldn't rely on your code.
In any case, in general - it is advised you study how to use a debugger. Once your code is compiling (and for that you'll need to get accustomed to the compilation error messages), you need to start debugging your code. I suggest you take some time to learn how to set breakpoints, set watches, and go step by step into your code. That skill is absolutely essential for a good developer.
Here's how I'd go about correcting the code ...
http://ideone.com/a0UMm -- compilation errors
http://ideone.com/ljUg1 -- warnings, but it works now
http://ideone.com/Qd0gp -- no errors, no warnings, test run ok
For 1. I used the "original code" as posted by you.
For 2. I used int main(void), declared the function get_number before defining main, added parenthesis in line 20, and added #include <stdlib.h>
For 3. I added return 0; before the final } of main. I also removed the extra output that messed up the ideone interface (it looks better on an interactive interface)
Edit more tests needed to complete the task of correcting the original code

Resources