Declaration statements in C - c

I seem to have a problem with declarations screwing up my math. Any advice or suggestions are highly welcomed.
Here's the code:
int num1, num2, num3, num4, op, ;
op = ((1==num3) || (2==num4));
num3 = (num1 + num2);
num4 = (num1 * num2);
I've been trying lots of arrangements and re-assignments. A lot has compiled, but when 5 + 5 = 2659043, there's a problem...

Not sure what you're trying to do, but this is what your code is doing:
int num1, num2, num3, num4, op, ;
This line informs the C compiler that it needs to allocate space for 5 integers (num1, num2, num3, num4, op), these integers can now be used as variables until the scope expires. Not sure why you have the last ',' you might want to remove that.
op = ((1==num3) || (2==num4));
If num3 is 1, or num4 = 2, then set op to 1 (true). Otherwise, set op to 0 (false).
num3 = (num1 + num2);
Self-explanatory: Add num1 and num2 and put the sum into num3.
num4 = (num1 * num2);
Self explanatory: Multiply num1 and num2 and put the product into num4.
Immediately I see an issue with your program. You are using these variables, but have not initialized them to anything. For example, how is there supposed to be a sum of (num1 + num2) if num1 and num2 do not have a value. Try this:
#include <stdio.h>
int main()
{
int num1, num2, sum;
num1 = 1;
num2 = 2;
sum = num1 + num2;
printf("sum = %d\n", sum);
}

Okay... there's a lot wrong here, but I'll go through what you posted in the comments point by point.
#include <stdio.h>
int main() {
/*Declare the active agents */
int num1=0, num2=0, num3=0, num4=0, op = 1 || 2 ;
You initialize your variables to zero here, except op, which you set to 1 (1 || 2, which is the boolean or, will return 1 (true), so as a result you set op to 1).
num3 = (num1 + num2);
num4 = (num1 * num2);
Here you set num3 and num4 both to zero, since num1 + num2 is 0 + 0 and num1 * num2 is 0 * 0. You want to move this down after your scanf's.
/* Information Extraction Method */
printf("YO MOFO!!!Press a number or hit the dirt!!\n");
scanf("%d", &num1);
printf("Since you didn't hit the dirt, how about another number?\n");
scanf("%d", &num2);
/* Menu (AKA Input */
printf("If you want to add, press 1 ,\nIf you want to multiply, press 2 ... \n\n ");
scanf ("%d", &op);
These printf's and scanf's are good. Good job.
/* PROCESS */
if (op = 1) {num3;};
if (op = 2) {num4;};
Three things here. First, op = 1 is assigning 1 to op. Same with op = 2. You want op == 1 and op == 2 as you have below. The result of this will be that op will always be 2 after these if statements.
The second thing is that, while a valid statement, num3; by itself won't do anything.
Finally, while it doesn't hurt anything, you don't need semicolons after your closing curly braces.
/* OutPut */
if (op == 1) {
printf("Alone, a toothpick is weak, but as part of a sum, your answer is:\n%d"), &num3;
};
if (op == 2) {
printf("Multiplied as a sum of it's parts, your answer is:\n%d"), &num4;
};
Here you're printing out the address of num3 and num4 instead of their values. This is part of the reason you're seeing large numbers that don't make sense, it's the address of num3 and num4 in memory. Only scanf needs the ampersand (&), printf does not. Also, as it stands, the actual value of these will always be 0 since your calculations are done before you get the numbers from the user.
EDIT: Actually, it turns out the reason you aren't getting the right numbers here is that you aren't passing the number to printf at all. You have num3 and num4 outside of the parentheses. There still shouldn't be an ampersand before the variable name, but it should look like this printf("Multiplied... is:\n%d", num4); Notice how num4 is inside the parentheses.
printf("\n\n\n\nMath frum da hud..... Yo. \n\n\nLOL\n >;]");
/* End Of Program */
return 0;
}
Edit: For clarity's sake, I've re-written it in a manner such that it should work the way you intended.
#include <stdio.h>
int main() {
/*Declare the active agents */
int num1=0, num2=0, num3=0, num4=0, op = 0;
/* Information Extraction Method */
printf("YO MOFO!!!Press a number or hit the dirt!!\n");
scanf("%d", &num1);
printf("Since you didn't hit the dirt, how about another number?\n");
scanf("%d", &num2);
num3 = (num1 + num2);
num4 = (num1 * num2);
/* Menu (AKA Input */
printf("If you want to add, press 1 ,\nIf you want to multiply, press 2 ... \n\n ");
scanf ("%d", &op);
/* OutPut */
if (op == 1) {
printf("Alone, a toothpick is weak, but as part of a sum, your answer is:\n%d", num3);
};
if (op == 2) {
printf("Multiplied as a sum of it's parts, your answer is:\n%d", num4);
};
printf("\n\n\n\nMath frum da hud..... Yo. \n\n\nLOL\n >;]");
/* End Of Program */
return 0;
}
HTH.

You did not initialize the variables, so their values are undefined (and probably not 0). You should initialize (like that, for example):
int num1 = 0, num2 = 0, num3 = 0, num4 = 0, op = 0 ;

Related

Am i doing a good job? I seem to have a lot of errors

int main() {
double num1, num2;
char f1;
printf("What to Count:");
scanf_s("%f", &num1);
scanf_s("%c", &f1);
scanf_s("%f=", &num2);
if (f1 = "+") {
printf("%lf\n", num1 + num2);
}
else if (f1 = "-") {
printf("%lf\n", num2 - num2);
}
else if (f1 = "*") {
printf("%lf\n", num1 * num2);
}
else if (f1 = "/") {
printf("%.2f\n", num1 / num2);
}
else if (f1 = "%") {
printf("%lf\n", num1 % num2);
}
else if (f1 = "#") {
printf("%lf\n", num1 ^ num2);
}
else {
printf("Invalid!\n");
}
system("pause");
return 0;
}
mvs said "a value of type "const char* " cannot be assigned to an entity of type "char"
"expression must have integral or unscoped enum type" etc.
You should get way more compiler warnings:
scanf_s("%f", &num1); here you have a parameter type mismatch. For double you need %lf. Fun fact: For printf("%lf\n", num1 + num2); you don't need the extra l as float parameters are passed as double anyway.
Same for scanf_s("%f=", &num2);. In this call you also require the user to enter = after the number.
scanf_s("%c", &f1); The scanf_s function requires an extra argument for %c format specifier: a value of type rsize_t indicating the size of the receiving array
if (f1 = "+") This is an assignment instead of a comparison. Use == instead.
That is also wrong type. "+" is a string while you only want to compare a character. That would be '+'.
As Jabberwocky pointed out, you are using all kind of functions without including the required headers. Don't do this.
printf("%lf\n", num1 ^ num2); What is this expression supposed to do? Bitwise XOR operator (^) is not allowed to be used with double values.
Same with printf("%lf\n", num1 % num2); The module operator mustn't be used with double values.
Additionally, you should always check return value of scanf and related function. Otherwise how would you know about errors?
From the operations that are not valid for double I assume you are supposed to use int instead.
As you do not use the lengh field of scanf_s you couls also use the standard functions instead.
A fixed version of your code could look like this:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void) {
int num1, num2;
char f1;
printf("What to Count:");
scanf("%d", &num1);
scanf("%c", &f1);
scanf("%d=", &num2);
int result = 0;
bool invalid = false;
if (f1 == '+') {
result = num1 + num2;
}
else if (f1 == '-') {
result = num1 - num2;
}
else if (f1 == '*') {
result = num1 * num2;
}
else if (f1 == '/') {
result = num1 / num2;
}
else if (f1 == '%') {
result = num1 % num2;
}
else if (f1 == '#') {
result = num1 ^ num2;
}
else {
invalid = true;
}
if (invalid)
{
printf("Invalid!\n");
}
else
{
printf("%d\n", result);
}
system("pause");
return 0;
}
I moved the printing into one place. That would make it easier to change type of calculations.
Output (in WSL):
What to Count:3+5=
8
sh: 1: pause: not found
Confusing assignment and equality operator:
Single '=' is used for assigning a value. For example char a = 5;
This assigns a value of 5 to the character variable a.
Double '==' is used for comparison, or checking equality. For example in this case, you have used single '=' in the conditions, which as you now know is an assignment operator. Replace it with a '=='.
Not including the header files:
The functions like printf and scanf are predefined in the header file <stdio.h>. Without including this, your compiler wouldn't recognize what print and scanf means.
Not checking input validity:
When prompting the user for input, always check the return value of scanf. Consider your users stupid, or even hostile who wants to find a way to crash your program. What if I were to enter 'asdf' when you asked for a character and vice versa? Scanf is a powerful function, but it was meant for parsing, not getting input as such.
Confusing '' and " ":
' ' is for a char variable, whereas " " is for a string variable. You've declared f1 as a character variable after main, not a string variable.
Indentation:
The curly braces are not in their right places. And you may as well omit them when the conditions only contain a single line of code.
Format specifier for double variable:
The format specifier for a double variable in the scanf statement is %lf, whereas a %f is used while printing.
You've also included a '=' operator in the third scanf statement. That could also render the program to work improperly.
int main(void)
{
double num1, num2;
char f1;
printf("What to Count:");
scanf_s("%lf", &num1);
scanf_s("%c", &f1);
scanf_s("%lf", &num2);
double resultdivide = num1 / num2;
double resultpow = pow(num1, num2);
double resultplus = num1 + num2;
double resultminus = num1 - num2;
double resultmult = num1 * num2;
if (f1 == '+') {
printf("%.0f\n",resultplus);
}
else if (f1 == '-') {
printf(".0f\n", resultminus);
}
else if (f1 == '*') {
printf("%.0f\n", resultmult);
}
else if (f1 == '/') {
printf("%.2f\n", resultdivide);
}
else if (f1 == '#') {
printf("%.0f\n", resultpow);
}
else {
printf("Invalid!\n");
}
system("pause");
return 0;
}
this is what i've come up with after brainstorming
looks messy but it actually works so im fine with it
but still can't figure out how to add the % function D:

Beginner question, do variables lose their values if inside multiple "while"s?

So I'm coding in C and compiling with gcc, I was attempting to create a simple code to display the Fibonacci sequence, you can input the amount of digits of the sequence you'd like to be displayed. Instead of the expected 0 1 1 2 3 5 8 etc. I get 0 1 1 2 3 4 5 6 7 etc. And I can't figure out why, if I remove the second "while" from the code, it works as intended, but I don't understand why. Do variables lose their values if they're inside multiple "while"s? Please help me figure this out. Again I'm a beginner so try to keep it simple.
My code:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
num1 = num1 + num2;
printf("%d ", num1);
cont++;
while(cont < num - 2){
num2 = num1 + num2;
printf("%d ", num2);
cont++;
}
}
return 0;
}
The answer to your main question is no. Variables work like this: We declare a variable somewhere in our code. This variable has a name, a value (we either initialize it or it has a random value) and an address in memory. Your program has access to this variable within the block which this variable has been declared. In this particular example, because you declared the variable cont in the main function, that means wherever you change the value of this variable in the main function that change takes place.
The problem in your code is that the variable num1 doesn't change accordingly and, in the whole program, has the value 1. That is the reason why the values printed change by 1. A piece of code that would solve this problem is the following:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0,temp;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
temp = num2;
num2 = num1 + num2;
num1 = temp;
printf("%d ", num2);
cont++;
}
return 0;
}
This code just stores the value of num2 in a variable temp, so we don't lose the value of num2 because we want to modify it and the new value of variable num1 must be the old value of variable num2.

Greatest Value to Lowest Value

Good day, I was practicing about C and encounter a problem. The problem was this part or somewhere here.
for (ctr = num2; ctr <= num1; ctr++)
For example the output is
Enter the value of n1: 3
Enter the value of n2: 10
4 6 8 10
I would like it to start from the greatest 10 8 6 4 instead of the least 4 6 8 10.
#include <stdio.h>
int main(void) {
int num1, num2, ctr;
printf("Enter value of n1: ");
scanf("%d", &num2);
printf("Enter value of n2: ");
scanf("%d", &num1);
for (ctr = num2; ctr <= num1; ctr++) {
if (ctr % 2 == 0)
printf("%d ", ctr);
}
return 0;
}
In your for, simply replace
ctr = num2; ctr <= num1; ctr++
with
ctr = num1; ctr >= num2; ctr--
Your current for loop first initializes ctr to num2. As we go through the loop, ctr is incremented such that it's value becomes num2 + 1, then num2 + 2, ..., then num1 - 1, then num1. After ctr is num1, the statement in the loop is executed one last time, then ctr is incremented and it's value becomes num1 + 1, which exceeds num1, causing the loop to end.
ctr takes on the values in {num2, num2 + 1, ... , num1 - 1, num1, num1 + 1}. The statement in the loop is executed for each of the values ctr takes except for num1 + 1.
To reverse this, you initialize ctr to num1 and as we go through the loop, ctr should be decremented such that it's value becomes num1 - 1, then num1 - 2, ..., then num2. After ctr is num2, the statement in the loop is executed one last time, then ctr is decremented and it's value becomes num2 - 1, which is less than num2, causing the loop to end.
ctr takes on the values in {num1, num1 - 1, ..., num2 + 1, num2, num2 - 1}. The statement in the loop is executed for each of the values ctr takes except for num2 - 1.
Notice how in both loops, the statement is executed when ctr takes on a value in {num2, num2 + 1, ..., num1 - 1, num1}. The only difference is that in the first loop, ctr starts with num2, moving up to num1, whereas in the second loop, ctr starts at num1, moving down to num2.
After making the above change, your program should function as expected. In the code below, I have (1) made the suggested change above and (2) included checks for the return value of scanf. It is not necessary to make change (2), but it is typically good practice to check the return value of scanf. For reference (from C99 Standard)
The scanf function returns the value of the macro EOF if an input
failure occurs before any conversion. Otherwise, the scanf function
returns the number of input items assigned, which can be fewer than
provided for, or even zero, in the event of an early matching failure.
In our case, we expect a scanf call of the form scanf("%d", &num2) to return 1. A return value not equal to 1 means there was an error in scanf. Currently, our function simply stops the program if there is an error. However, using the feof and ferror functions, one would be able to know the type of error that occurred and the programmer can choose to make the program behave differently depending on the type of error. For brevity I have omitted the use of feof and ferror (both from <stdio.h>), though I thought I would mention them since we are on the topic of scanf errors.
It is also worth noting that you need to be careful that the user does not enter a number for num2 that is equal to INT_MIN (a macro defined in <limits.h>), the minimum value for an object of type int. While assigning INT_MIN to an int such as num2 is not by itself wrong, if num2 is INT_MIN, eventually ctr will equal num2, the statement in the loop will be executed one "last" time, but then num2 will be decremented which would mean trying to assign to num2 a number lower than the minimum value for an object of type int. That is, the program will have undefined behavior. The likely result of setting num2 to INT_MIN is that the loop will run forever.
Program
#include <stdio.h>
#include <stdlib.h>
int main(void){
int num1, num2, ctr;
printf("Enter value of n1: ");
if (scanf("%d", &num2) != 1) {
printf("scanf: error\n");
exit(EXIT_FAILURE);
}
printf("Enter value of n2: ");
if (scanf("%d", &num1) != 1) {
printf("scanf: error\n");
exit(EXIT_FAILURE);
}
for (ctr = num1; ctr >= num2; ctr--)
if (ctr % 2 == 0)
printf("%d ", ctr);
printf("\n");
return 0;
}
Example Session
Enter value of n1: 3
Enter value of n2: 10
10 8 6 4

No errors in code but the program stopped working

I am using code blocks and it says my code has no errors, Yet when I run the program it stopped working as I tried to give an input. Please keep in mind that my programming class has just started and I do not know much at all.
Here is the code to my program:
#include <stdio.h>
int main()
{
int num;
int num1, num2, num3, num4;
printf("Please insert a number here:\n");
scanf("%d\n", num);
printf("When value of variable num is 2,\n");
num1 = num +1;
printf("\nThe value of num after using num + 1 is: %d", num1);
num2 = num +=1;
printf("\nThe value of num after using num +=1 is: %d", num2);
num3 = ++num;
printf("\nThe value of num after using ++num is: %d", num3);
num4 = num++;
printf("\nThe value of num after using num++ is: %d", num4);
return 0;
}
and when I run the program it stopped working.
So, how can I fix this error?
Thanks in advance.
You have an error in the scanf call.
It should be
scanf("%d", &num);
Note the & before num. Scanf expects a pointer to the variable that have to be filled in with the input value.
Regarding your code and the question in your comment you should note that:
num1 = num +1;
num1 is num plus one
printf("\nThe value of num after using num + 1 is: %d", num1);
num2 = num +=1;
num is incremented by 1 then assigned to num2 with the new value
printf("\nThe value of num after using num +=1 is: %d", num2);
num3 = ++num;
num is again incremented by 1 and then assigned to num3
printf("\nThe value of num after using ++num is: %d", num3);
num4 = num++;
num at its actual value is assigned to num4 then num is incremented by 1 (the ++ operator is after the variable so the increment occurs after the assignment)
printf("\nThe value of num after using num++ is: %d", num4);
What you write inside your printf is not exact. You are not printing the value of num but num1, num2,...
As
num4 = num++;
num4 is different than num (it's num minus one)
Yeah, I think you still have to use
scanf("%d", &num);
even for int since it's still reading numeric data.
I think your answer changed halfway as well after ans2 because you used num2 = num +=1;. The += is like using num = num + 1;. Which would modify the value of num. So, ans3 and ans4 became different from what you expected. E.g. if you entered num as 2, ans 3 and ans4 would equal 4 instead of 3. If you want to get notified about this, you can put some print statements such as printf("\n Just printing value of num at this moment: %d",num); at various places in your code to observe the changes.
The way you are taking the input is wrong. You need to add an '&' sign before all the variables except for strings. So change the statement to scanf("%d",&num);
And also from reading your code,you want to initiate num1 if value of num=2.
printf("When value of variable num is 2,\n")
but your code does initiate it for any value of num. For avoiding that use an if loop as
printf("When value of variable num is 2,\n")
if(num==2)
{num1=num+1;}
else
{num1=0;
//or some other condition you wish
}
//and rest continues...

C: If statement not working

if (num2 != 0)
printf("\nInput 3 / Input 2 (int) %12d", divide);
else if (num2 == 0)
printf("\nInput 3 / Input 2 (int) DIV/0");
if (flt4 != 0)
printf("\nInput 2 / Input 1 (double) %16.3f", divide2);
else if (flt4 == 0)
printf("\nInput 2 / Input 1 (double) DIV/0");
When I set num2 or flt4 equal to 0 the program crashes. Otherwise it works perfectly fine. I was looking over the reading about if/else statements and I believe my formatting is correct, but there is obviously an error.
Thanks.
EDIT:
The code where i define divide is:
void calculate (int num1, int num2, int num3, float flt4,int* sum,int* mult,
int* mod,int* divide,double* mult2,double* divide2)
{
*sum = num1 + flt4;
*mult = num1 * num3;
*mod = (num1/10)%10;
*divide= num3 / num2;
*mult2= num1 * flt4;
*divide2= (double)num2 / num1;
return;
}
My question then is, how do I structure this program so if it divides by zero I can display that in the print function.
Most likely you are dividing by zero. The divide variable is set before the 'if' and you perform that operation anyway. Put that inside the first 'if', so it will divide by the num2 iff num2 is different than zero.
Edit:
It should look like that:
if (num2 != 0) {
divide = something / num2;
printf("\nInput 3 / Input 2 (int) %12d", divide);
}

Resources