For loop in a function brings up random numbers [duplicate] - c

This question already has answers here:
What will happen if '&' is not put in a 'scanf' statement?
(6 answers)
Closed 4 years ago.
So I'm writing a program about finding the sum number of all ranges for instance, if I enter a 1 and then a 10 it should display 55, but instead it display some long random number. Does anyone have a clue what's wrong with this code? Thanks!
#define <stdio.h>
calculateSum(int lowNumber, int highNumber);
int main()
{
int lowerNumber,
higherNumber;
scanf("%d", lowerNumber);
scanf("%d", higherNumber);
printf("The sum of all ranges is: %d", calculateSum(lowerNumber, higherNumber));
int calculateSum(int lowNumber, int highNumber)
{
int total;
for(int x = lowNumber; x <= highNumber; x++)
{
total = total + x;
}
return total;
}

You're not initializing total before its first use as a rvalue (which is the RHS of assignment total = total + x;) thus its value remains undefined (and indeterminate.)

In addition to #biplls answer there is also another issue:
int lowerNumber,
higherNumber;
scanf("%d", lowerNumber);
scanf("%d", higherNumber);
is UB (produces a warning on compilation and a SEGFAULT during runtime). printf expects an int*, not int. The correct code would be
int lowerNumber,
higherNumber;
scanf("%d", &lowerNumber);
scanf("%d", &higherNumber);

A few errors here
it's #include <stdio.h> not #define
When using scanf you have to add an & before the var you read into (in this case!! )
The main fn doesn't return anything, it should be returning 0 (normally) (apparently I'm wrong on this , main returns 0 implicitly from C99)
Main fn isn't closed before you write the next fn
total should be set to 0
for loop initialization is allowed only in C99
It is a good idea to declare the return type of the prototype
fixing all this
#include <stdio.h>
int calculateSum(int lowNumber, int highNumber);
int main()
{
int lowerNumber,
higherNumber;
scanf("%d", &lowerNumber);
scanf("%d", &higherNumber);
printf("The sum of all ranges is: %d\n", calculateSum(lowerNumber, higherNumber));
return 0;
}
int calculateSum(int lowNumber, int highNumber)
{
int total;
total = 0;
for(int x = lowNumber; x <= highNumber; x++)
{
total = total + x;
}
return total;
}
Running the above
$ ./sum
1
10
The sum of all ranges is: 55

Related

C program giving extremely wrong answer

Program takes an integer input num from the keyboard and computes the sum of square of i for all I from 1 to num (inclusive).
#include <iostream>
#include <math.h>
int main()
{
int num;
int total;
printf("Please enter a number:");
scanf("%d", &num);
for (double i = 1; i <= num; i++) {
total += (i*i);
printf("%d", total);
}
}
The code above compiles correctly, but when inputting 5 it prints 15143055. Why is it doing this?
#include <iostream> is c++. #include <math> is not used. total is uninitialized. Comparing floating point values may not behave the way you want, so using a (unsigned) integer type instead as a loop counter. Loop values by convention start at 0 instead of 1 in c (you could increment i fist thing in the loop to avoid the double (i+1) but this will be optimized out anyways). Also, your loop not run for a negative value so just require unsigned values. As you sum integers the result ought to be an integer, but double would give you a larger range so I left it as such. Missing return:
#include <stdio.h>
int main() {
unsigned num;
printf("Please enter a number: ");
scanf("%u", &num);
double total = 0.0;
for (unsigned i = 0; i < num; i++) {
total += (i+1)*(i+1);
}
printf("%lf\n", total);
return 0;
}
and the resulting output:
Please enter a number: 3
14.000000

What makes the difference between declaring variable = 0 and leaving variable by itself? [duplicate]

This question already has answers here:
What happens to a declared, uninitialized variable in C? Does it have a value?
(9 answers)
Closed 2 years ago.
I was looking through 'while loop' and figured that the result was different when I declared variables = 0 and when I did not in the loop.
I am not sure why it makes different result...
Here`s example!
#include<stdio.h>
int main(){
int even=0;
int total=0;
do{
total+=even;
even+=2;
}while(even<=100);
printf("total : %d", total);
return 0;
}
result
total : 2550
#include<stdio.h>
int main(){
int even;
int total;
do{
total+=even;
even+=2;
}while(even<=100);
printf("total : %d", total);
return 0;
}
result
total:2551
The following is undefined behaviour:
int even;
int total;
total += even;
Before reading from a variable with automatic storage duration, you must initialize it or assign to it.

For loop function too few arguments to function

Hi I'm somewhat very new to programming and I just came across this new error called "too few arguments to function" and have no idea what this means. I've been trying to figure out for a while whats exactly wrong with the code, but I'm having no luck so far. Any advice? Thanks in advance!
int sumRange(int lowerNumber, int higherNumber);
int main()
{
int lowerNumber,
higherNumber,
sum;
scanf("%d%d", lowerNumber, higherNumber);
printf("\nThe smaller number is %d and the larger number is %d", lowerNumber,higherNumber);
printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(sum));
}
int sumRange(int lowerNumber, int higherNumber)
{
int x,
total;
for(x = lowerNumber; x <= higherNumber; x++)
{
total = total + x;
}
return x;
}
You have to initialize the "total".
int sumRange(int lowerNumber, int higherNumber)
{
int x,
total;
total = 0;
for(x = lowerNumber; x <= higherNumber; x++)
{
total = total + x;
}
return total;
}
Function main() lacks initial { and final }.
Also, in function sumRange, you may want to return total, not the x.
Also, in line "printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(sum));"
you are calling sumRange with only one parameter. You should call it with two parameters: sumRange(lowerNumber,higherNumber)
I just came across this new error called "too few arguments to function" and have no idea what this means
It means that the function wasn't supplied all of the arguments that are present in its definition.
The function was defined here:
int sumRange(int lowerNumber, int higherNumber);
As you can see, there are two arguments in the definition: int lowerNumber, int higherNumber. But your use of that function here:
printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(sum));
Only supplies that function with one argument. Since you are reading the arguments in with scanf, the correct use would be:
printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(lowerNumber, higherNumber));

Why do I get an endless loop from my code?

#include <stdio.h>
int main() {
int num;
int square;
int sum;
while (num) {
if (num > 0) {
scanf("%d", &num);
square = num * num;
sum = square + sum;
printf("%d \n", sum);
}
}
return 0;
I'm trying to produce the sum of squares for positive numbers, and when the first negative number is inputted, the loop ends. Result needs to be left justified by 10 spaces.
The code has undefined behavior: the first time you test the value of num, it is uninitialized. If by chance it happens to not be negative, you scan a new value and add its square to uninitialized variable sum, producing more undefined behavior, it the value input was negative, the next test fails and the loop repeats forever.
Left justifying in a 10 space width is obtained with the %-10d conversion format.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int num, square, sum = 0;
while (scanf("%d", &num) == 1 && num != 0) {
square = num * num;
sum = square + sum;
printf("%-10d\n", sum);
}
return 0;
}
If you want the number to be right justified in a 10 space width so all output values align properly, use the %10d format instead.
If you input large numbers or too many items, you will eventually exceed the range of type int. You can try and increase the range of variables square and sum by making them long long int or even as commented by PeterJ unsigned long long int, and allow for larger values to be computed:
int main(void) {
int num;
unsigned long long square, sum = 0;
while (scanf("%d", &num) == 1 && num != 0) {
square = (long long)num * num;
sum = square + sum;
printf("%21llu\n", sum);
}
return 0;
}
Note that (long long)num * num will be converted to unsigned long long that has a range at least as large in the positive values.
Using uninitialized variable leads to undefined behavior.You are using uninitialized local variable num in your while loop. num can have any value in it. If the value is smaller than 0 the loop will run forever. It will also loop for ever if the value smaller than 0 is entered using scanf.
For undefined behavior please check lines from standard
6.3.2.1 Lvalues, arrays, and function designators
If the lvalue designates an object of automatic storage duration that
could have been declared with the register storage class (never had
its address taken), and that object is uninitialized (not declared
with an initializer and no assignment to it has been performed prior
to use), the behavior is undefined.
I hope, this might help ending the loop
#include <stdio.h>
int main() {
int num = 0;
int sum = 0;
while (num >= 0) {
scanf("%d", &num);
if (num>=0) {
sum = ( num * num ) + sum;
printf(" %d\n", sum);
}
}
return 0;
}

I want to code fibonacci series program in C but I am getting the last element as negative [duplicate]

This question already has answers here:
Number at f(93) in fibonacci series has negative value, how?
(3 answers)
Closed 5 years ago.
I don't know why am I getting the last number as negative.
I want to get the output as 0 1 1 ... 'n' numbers (fibonacci series)
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int a=-1,b=1,c=0;
for(int i=0;i<n;i++)
{
c=a+b;
printf("%d",c);
a=b;
b=c;
}
return 0;
}
Yes, it is definitely out of int range
1836311903 //before last
-1323752223 //last
the max int is 2,147,483,647
If you want more than n=48, you must declare a,b,c as long type
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
long a=-1,b=1,c=0;
for(int i=0;i<n;i++)
{
c=a+b;
printf("%ld\n",c);
a=b;
b=c;
}
return 0;
}

Resources