I am writing a C program to sum up prime numbers below a certain limit (9 for now). I expect 17 but the compiler gave me an unexpected output of 32781.
#include <stdio.h>
#include <stdbool.h>
bool isprime(int n);
int main(){
const int LIMIT=9;
int sum;
for (int j=1;j<LIMIT;j++){
if (isprime(j)){
sum+=j;
}
}
printf("%d",sum);
return 0;
}
bool isprime(int n){
if (n<=1){
return false;
}
else{
for(int i=2;i<n;i++){
if (n%i==0){
return false;
break;
}
}
return true;
}
}
Does anyone understand why this happened?
You declarred int sum; but didn't give sum a starting value, so it's basically reading garbage from memory. In c you need to initialize your variables properly. int sum = 0; should fix the problem.
If you are using clang as your compiler, compiling using -Wall should warn you about this.
Local variables are not initialized, so you need to initialize at declaration or before use.
int sum = 0;
or...
int sum;
for (sum = 0; bla; bla)
If the variable had been declared globally (outside of any function... main is a function) it will automatically initialize to 0.
#include <stdio.h>
int a;
int main(void)
{
int b;
printf("%d\n%d\n", a, b);
return 0;
}
Variable 'a' will be 0 and 'b' will be garbage because it's an uninitialized local variable.
Related
#include <stdio.h>
main()
{
int n;
n+=2;
printf("sum=%d", n);
return 0;
}
Here the 'Sum'=2
Another program:-
#include <stdio.h>
main()
{
int n,a=2;
n+=a;
printf("sum=%d", n);
return 0;
}
here the output 'sum' = 3
WHY so?? What is the problem in the code??
This is Undefined Behavior. Using uninitialized variables (n in both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll set n to a specific value in both codes, you'll start getting consistent results.
This is UB (Undefined Behavior):
main()
{
int n;
printf("sum=%d", n);
return 0;
}
This is not:
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
When you don't assign a value to a local variable in C, its value is undefined. So in some cases it will be 0, in some 1, in some, something else entirely. You cannot know what it will be and you should never rely on it. Instead, initialize your local variables:
int n = 0; // initialization
n += 2;
printf("sum=%d", n); // will always print 2
#include <stdio.h>
int main();
{
int a;
int b;
int c;
a = 1;
b = 1;
c= 2;
for ()
{
a = c + b;
printf(a,"\n");
b = c + a;
printf(b,"\n");
c = a + b;
printf(c,"\n");
}
}
I am a beginner at C and am trying to write a program to list the Fibonacci sequence.
This is what I have so far. I know I have at least two issues, one being the for loop. How would I make it an infinite loop?
My second issue that I'm running into is this error message
"prog.c:3:1: error: expected identifier or '(' before '{' token
{
^"
If someone could help that would be much appreciated.
Remove the ; after int main() -- should take care of the compiler error
while(1) instead of for() -- will run an infinite loop
Here is the working code for Fibonacci series
#include <stdio.h>
void main()
{
int a;
int b;
int var_z;
a = 1;
b = 1;
for(int i = 0;i < 10;i++)
{
printf("%d\n",a);
printf("%d\n",b);
a = a+b;
b = a+b;
}
}
Eg. https://eval.in/1013468
/* Fibonacci series */
#include
int main()
{
long int a =0;
long int b=1;
long int c=1;
int n,d=1;
printf(" Enter the number of
terms ");
scanf("%d",&n);
do
{
printf("%d\n",c);
c=b+a;
a=b;
b=c;
d=d+1;
}
while(n>=d);
return 0;
}
This is one way you might do it.
#include <stdio.h>
int main()
{
unsigned int a;
unsigned int b;
unsigned int c;
a = 0;
b = 0;
c = 1;
while(1)
{
if (c < b)
break;
printf("%u\n",c);
a = b;
b = c;
c = a + b;
}
}
Modified to use unsigned int and change comparison based on comment.
Bobby
How to read this particular compiler error:
prog.c:3:1: error: expected identifier or '(' before '{' token { ^
This is telling you that the error occurs on line 3:
1: #include <stdio.h>
2: int main();
3: { // <------ compiler is complaining about this line
and that it's seeing a { where it shouldn't. The only time it should see a { is after a function declarator (function name plus argument list) or after an identifier (for a struct, union, or enum definition).
The problem is that you shouldn't have the semicolon after int main Because of it, the compiler is treating int main() as a declaration, not the beginning of a function definition.
Remove that semicolon and the error will go away.
Important lesson here - the compiler doesn't tell you where you actually made the error, but where that error prevents it from translating the code. If you have a deeply nested loop, like
for (...)
{
for (...)
{
for (...)
{
and you forget to put in the closing brace on the innermost loop, the compiler won't say "you forgot to put a closing brace on this innermost loop"; instead, it will complain about a line some ways down, either because it's reached the end of the program or the next function definition without seeing the closing } of the previous function.
How would I make it an infinite loop?
The syntax for an infinite loop is either while(1) or for(;;). Doesn't matter which you use, the compiler should (should) generate the same code for both. Like other people have said, though, Fibonacci numbers get very large very quickly, too large for a native integer data type to represent. You'll start seeing overflow errors after computing the 50th F number or so.
There are some errors with your code, the semi colon after main is wrong, your algorithm dont output fib sequence and the for loop it is typed incorrect.
#include <stdio.h>
int main() //;<-- doesn't contain semicolon
{
/* use a better variable name for clarity
int a; --> a
int b; --> last number
int c; --> sum
a = 1;
b = 0;
*/
int a = 1;
int last = 0;
int sum;
for (;;) // infite for loop needs 2 semicolons to work
{
printf("fib : %d\n", last);
sum = a + last;
last = a;
a = sum;
}
}
By the way, you should limit your for loop or else it going to overflow your int variable. long unsigned a,sum,last would give you more bits to store.
I have recently started coding in C, and am doing some stuff on project Euler. This is my code for challenge three so far. The only problem is when I run the compiled code it throws a segmentation fault. I think it may be due to a pointer I called, the suspect pointer is underneath my comment. I did some research into the subject but I cant seem to be able to fix the error. Any advice?
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
bool is_prime(int k);
int * factors(int num);
int main(){
int input;
while (true){
printf("Enter a number to get the prime factorization of: ");
scanf("%d", &input);
if (is_prime(input) == true){
printf("That number is already prime!");
}else{
break;
}
}
//This is the pointer I think is causing the problem
int * var = factors(input);
int k;
for (k = 0; k < 12; k++){
printf("%d", var[k]);
}
}
bool is_prime(int k){
int i;
double half = ceil(k / 2);
for (i = 2; i <= half; i++){
if (((int)(k) % i) == 0){
return false;
break;
}
}
return true;
}
int * factors(int num){
int xi;
static int array[1000];
int increment = 0;
for (xi = 1;xi < ceil(num / 2); xi++){
if (num % xi == 0){
array[increment] = xi;
increment++;
}
}
}
The factors function has no return statement. It's supposed to return a pointer but it doesn't return anything.
Side note: Enable your compiler's warnings (e.g., with gcc -Wall -Wextra). If they're already enabled don't ignore them!
Your function is declared as
int * factors(int num);
but it's definition doesn't return anything and yet you are using it's return value in assignment. This triggers undefined behavior. It will compile if compiled without rigorous warnings and the return value will most likely be whatever random value happened to be left in the return register (e.g. EAX on x86).
C-99 Standard ยง 6.9.1/12 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
im a 1st grader when it comes to c and need help with storing 5 random values in an array and outputting them. Heres where am at.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);
int value;
int main(void) {
struct score_card test;
randomize;
int i;
for(i = 0; i <= 4; i++){
printf("%d\n", dice_rolls[i]);
}
printf("\n");
return 0;
}
int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
value = rand() % 6 + 1;
dice_rolls[i] = value;
}
}
The output is :
6294304
6294308
6294312
6294316
6294320
the goal was to use modular division to get values from 1 -->6 and store them in the dicerolls array.
I see two immediate problems.
First. you're not terminating your random numbers with a newline. That's why they're all strung together in a big sequence. Change your output line to:
printf("%d\n", &dice_rolls[i]);
Secondly, you're not actually calling randomize. The correct way to call it is with:
randomize();
The statement randomize; is simply an expression giving you the address of the function. It's as useless in this case as the expression 42; which also does nothing. However it's valid C so the compiler doesn't necessarily complain.
#include <stdio.h>
int main (void)
{
int n, x;
int factorial (int n)
{
if (x<=0)
{
printf("x equals: ");
return 1;
}
else
{
return n * factorial (n-1);
}
f(x)=f(x-1)+2; //says error is here
}
return 0;
}
I've tried some things and can't get it to work. I could just be overtired and looking past the smallest thing but help would be much appreciated! Thanks :)
You cannot declare a function definition inside of main() or any other function ... function definitions have to be stand-alone and cannot have embedded function definitions inside of them.
Also I'm not sure what you're doing on the line that you've marked as an error since f() is not a defined function, so you can't call it. Furthermore, it would need to return some type of l-value, such as a pointer to a static variable declared inside the function, or a pointer passed by reference to the function and even then the syntax is not right since there would be a required dereference ... so basically you can't do what you're doing on that line.
To get something that compiles, try
#include <stdio.h>
int factorial (int n)
{
if (n <= 0)
{
return 1;
}
else
{
return n * factorial (n-1);
}
}
int main (void)
{
int x;
x = factorial(5);
printf("Factorial of 5 is equal to %d", x);
return 0;
}
Use indentation to see possible problems with scope:
#include <stdio.h>
int main (void)
{
int n, x;
int factorial (int n)
{
if (x<=0)
{
printf("x equals: ");
return 1;
}
else
{
return n * factorial (n-1);
}
f(x)=f(x-1)+2; //says error is here
}
return 0;
}
As far as I can remember, C doesn't have closures.
A function cannot be defined inside another function. However gcc allows it as an extension. You have defined a function named factorial but are trying to use f which hasn't been declared anywhere.