#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.
Related
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.
I am new to the C.Sc course and we are taught C program.
I was trying some of the basic stuff. Currently I am learning User-Defined-Function.
The following code is the one I was trying with. I know it is pretty simple but I am not able to understand why it is producing such weird output.
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
}
int add(int a) //function definition
{
int result;
for(int i = 0; i < a; i++)
{
result = result + i;
return result;
}
}
The output for 1 is 32743
The output for 2 is 32594
The output for 3 is 32704
The weird thing is output change each time for the same number.
It's just weird considering my experience in C.Sc. till date. Kindly explain what the program is doing.
This is the right place to post problems like this. Right?
You forget to initialize result.
int result = 0;
Explanation : If you do not initialize the variable, it will have a "random" number, and then you are going to get "random" output
Also :
You also forgot to return something if a = 0, or a negatif number !
And your main NEED to return a int.
Also, there is no point to do a loop since you return inside of it, you always going to return 0 in the loop.
Here is a correction of your code :
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
return 1;
}
int add(int a) //function definition
{
int result = 0;
for(int i = 0; i < a; i++)
{
result = result + i;
}
return result;
}
Exemple with 10 as input : https://ideone.com/6BjM6y
You need to initialize result,
int result = 0;
In your code, result is not initialized so at the
result = result + i;
line, you use whatever value result has and it's not possible to determine which value is that because it's a garbage value.
In c, variables are not automatically initialized for performance reason, with a few exceptions, the most notable are
Local variables with static storage class.
Global variables.
when you leave a variable uninitialized, then trying to read it's value is considered undefined behavior.
In response to your comment
The problem is that you return after adding 0 to result which is 0, so move the return result; outside of the for loop and it should work.
You need to initialize the variable result. Since it is bot initialized, the compiler initializes it with a default value, which could be a "funky" mumber. To fix this, initialize result in your Add() function to:
int result = 0;
Another thing: your return statement is inside the for-loop. This means that the for-loop will terminate at the end of the first loop since there is a return statement that will terminate the function. To fix it, change your function to:
int result;
for(int i = 0; i < a; i++)
{
result += i; // shorthand way of writing result = result + i. Same end result
}
return result; // should be outside the loop
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.
I fixed the code from this question so that it would compile:
#define text ();
#define return &argv;return
int *** emphasized () {
static int x, *argv = &x, **xpp = &argv;
puts("\r10 11 11");
return &xpp;
}
int main (int argc, char *argv[]) {
int a;
int n = 10;
printf("%d",n);
n++;
printf("%d",n);
a = n++;
printf("%d",n);***emphasized text***
return 0;
}
In the original question, the asker said:
Output= 10 11 11 why it's not increment value of n in second increment operator
Which is why emphasized() does something funny. I was trying to come up with a way that took the asker's literal code to make it do what he/she said it did. To that end, I treated the ***emphasized text*** as part of the source.
My question is: How would emphasized() be changed so that it renders the 10 11 11 output without calling any output function? I am hoping to observe a way to alter the output rendered by the printf() to standard output to add the spaces but botch the last number.
Since this question is labeled with obfuscation, if the solution involves adding more #defines, have at it.
n is incremented to 12 but as n is never printed its value doesn't matter.
Run that crap through the preprocessor and you'll see why.
There is a #define that voids all the printf statements.
The actual output comes from the puts in emphasized.
Here's the original code:
#define text ();
#define printf(a,b) (void)0
#define return &argv;return
int *** emphasized () {
static int x, *argv = &x, **xpp = &argv;
puts("\r10 11 11");
return &xpp;
}
int main (int argc, char *argv[]) {
int a;
int n = 10;
printf("%d",n);
n++;
printf("%d",n);
a = n++;
printf("%d",n);***emphasized text***
return 0;
}
Here's the code after being run through the preprocessor:
int *** emphasized () {
static int x, *argv = &x, **xpp = &argv;
puts("\r10 11 11");
&argv;return &xpp;
}
int main (int argc, char *argv[]) {
int a;
int n = 10;
(void)0;
n++;
(void)0;
a = n++;
(void)0;***emphasized ();***
&argv;return 0;
}
Note that the printf statements don't appear in the preprocessed code; the value of n isn't being displayed to the console at all in this version. The output comes from the emphasized function.
n is incremented twice, and it is also printed out, exactly as you'd expect.
But text has been #defined to be a pair of parentheses and a semicolon: ();, and return is replaced with &argv;return
So the code
***emphasized text***
return 0;
becomes:
***emphasized();***
&argv;return 0;
or slightly less oddly formatted:
***emphasized();
***&argv;
return 0;
so the printfs do exactly what it looks like they're going to do, and then emphasized() is called, and it backs up the cursor with a '\r' (carriage return, no line feed) and prints out your 10 11 11.
All the asterisks are just for show, dereferencing pointers but not using the results.
Here's a slightly less obfuscated version that remaps each printf() call to something that ends up constructing the output as described by the original asker. It is slightly more straightforward since it doesn't define a silly emphasized() function. It also avoids unnecessarily dereferencing argv, to avoid undefined behavior in the case that argc is 0.
This version also has the property that the program will also behave as the asker described if the ***emphasized text*** string is removed from the program.
#include <stdio.h>
#define printf(f,x) printf(x>11?"%d\n":"%d ", x>11?x-1:x);
#define emphasized &argv;
#define text if(0)
#define return &argv;return
int main (int argc, char *argv[]) {
int a;
int n = 10;
printf("%d",n);
n++;
printf("%d",n);
a = n++;
printf("%d",n);***emphasized text***
return 0;
}