gcc seems to compile my code wrong? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am rather new in C and i was trying to solve some exercises in my textbook and encountered a wierd Problem. although my Task is undeniably easy the program just wont work right. after some Trials it seems that the fault is on the Compiler but as much as this sounds unreasonable its the only justification i can bring up
without any further delay here is the code
#include <stdio.h>
double power(double n, int p);
int main(void)
{
double x, xpow;
int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2)
{
xpow = power(x,exp);
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
double power(double n, int p)
{
double pow = 1;
int i ;
if ( n == 0 && p == 0)
{
printf("0 to zeroth power is undefined\nwe will use therefor 1 instead\n");
p = 1 ;
}
if (p >= 0)
{
for (i = 1 ; i <= p ; i++);
pow *= n ;
}
else
{
for (i = -1 ; i >= p ; i--);
pow *= 1/n ;
}
return pow;
}
the programs intent is clear the problem is when I input some test cases the output is wrong
like
(5 2)
the output should be 25 but I get 5
(5 6)
the output should be 15625 but i get 5
after examining this problem with gdb I found that instead of initializing i to 1 it is initialized to 3 for no obvious reason and with the second input i is initialized to 7
i want to know why
I'm using gcc.

Why do you blame the compiler, I would blame my eyes first you have an extra semicolon in both your for loops
for (i = 1 ; i <= p ; i++);
change it to
for (i = 1 ; i <= p ; i++)

Related

finding the sum of digits? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried this problem using for loop but i did not got the correct output as specified . i do not know what is the problem in my code ?
#include <stdio.h>
int main()
{
int T,N;
scanf("%d %d" ,&T,&N);
for(int i=N;i>0;i=i/10)
{
int r=N%10;
int sum=0;
sum=sum+r;
printf("The sum is : %d" ,sum);
}
}
The sum is : 5The sum is : 5The sum is : 5The sum is : 5The sum is : 5
The output is coming like this while we just need sum of digits printed
for(int i = N; i > 0 ; i = i/10)
{
int r = N % 10; // calculating remainder of UNMODIFIED input, so will
// ALWAYS be last digit
int sum = 0; // you are initializing the sum to 0 for every single iteration
sum = sum + r; // so this will *always* result in 0 + N % 10
printf("The sum is : %d", sum);
}
To fix, you need to initialise the sum just once to collect all of the single digits. Additionally, you need to use the modified value:
int sum = 0;
for(int i = N; i > 0 ; i = i/10)
{
int r = i % 10;
// ^ (!)
sum += r; // alternative variant...
printf("The sum is : %d\n", sum);
// ^^ for better output formatting
}
Until now we are still printing the sum with every iteration as well. That might be useful, if you want to follow how the sum evolves (assuming input was 1210):
The sum is 0
The sum is 1
The sum is 3
The sum is 4
But actually, you'd rather want to print only the result, wouldn't you? So you'd move the printing out of the loop as well:
for(...)
{
...
}
printf("The sum is : %d\n", sum);
Alternative variant: If you don't need the value of N afterwards any more anyway, you can iterate directly on it:
for( ; N > 0; N /= 10)
// ^ empty initialization, nothing to be done...
{
int r = N % 10; // NOW using N is fine...
...
}
Finally: if you compare with != instead of >, you can cover negative intput (as you use signed integers...) as well.
Edit according to question:
it asked input and output like this. Input 3 12345 31203 2123 Output 15 9 8
Well, in this case, you need a double loop:
int t;
// well, actually, you should check if you did get correct input:
if(scanf("%d", &t) != 1))
{
// invalid input
// appropriate error handling, e. g. printing a message and:
return -1;
}
for( ; t > 0; --t) // handles the number of tasks to solve
{
int n; // inside loop: read in a new value with every task
scanf("%d", &n); // TODO: check input, see above
int sum = 0;
for(...) { ... } // loop handling the input value, see above
printf(...);
}

Understanding this output from a factorial recursion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
In this factorial recursion "printf" outputs 2 6 8, Can't understand why...
#include <stdio.h>
int f(int n)
{
int k;
if (n==1)
return 1;
else
k = n*f(n-1);
printf("%d ",k);
}
int main()
{
f(4);
}
The original version of the code in the question was:
int f(int n) {
int k;
if (n == 1)
return 1;
else
k = n * f(n - 1);
printf("%d ", k);
}
int main() {
f(4);
}
This code has undefined behavior because you do not return a value properly if n != 1, causing the calling code to use an unpredictable value in its own calculation. The behavior is undefined, anything can happen.
Adding the return statement fixes this issue. Note however these extra points:
variable k is useless in the f function.
f should return 1 for an argument of 0.
you should output a newline after the number and return 0 in main.
Here is modified version:
#include <stdio.h>
int f(int n) {
if (n <= 1)
return 1;
else
return n * f(n - 1);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d! = %d\n", i, f(i));
}
return 0;
}
There are many mistakes you are making here:
printf("%d ",k);
this line is never going to be executed because in any case if() else clause will return before it.

C Function: Count the occurrences of a digit in an integer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm receiving Output: 1. I should count the number of times a digit appear in an integer, for example, for number 1222345 and n = 2 Should appear 3 times.
int countOccurrences(int n, int num)
{
int i,k;
i=0;
while(num!=0)
{
k=num%10;
num=num/10;
if(k==n)
{
i++;
}
}
}
// Main
void main()
{
int num= 1222345;
int n = 2;
printf("Occurance of a number: %d", countOccurrences(n,num));
}
You have undefined behavior in the code. The function is supposed to return an int and it didn't.
Solution is to add return i in the end of other function. This will give you correct result. In the countOccurrences() function
...
if(k==n)
{
i++;
}
}
return i;
}
I was skipping the discussion of error check and all that. As chux mentioned for n<=0 case you might want to add a different way of handling it but you didn't add it. Atleast consider those case and put an error message on whatever input you need.
Some corner cases are
n=0,m=0.
Negative value of n or m.
Put a return on your countOccurrences function please
int countOccurrences (int n, int num) {
int i, k;
i = 0;
while (num! = 0)
{
k = num% 10;
num = num / 10;
if (k == n)
{
i ++;
}
}
return i; }
As other have pointed out, there are important issues with your code.
Here is a recursive solution that you may find interesting:
int countOccurrences(int n, int num)
{
int count = ((num % 10) == n);
return (num < 10) ? count : count + countOccurrences(n, num / 10);
}
Few general remarks about your code:
When using printf(), you should #include <stdio.h>.
main() should return int.
Place spaces around operators and format your code consistently. This k = num % 10; is more readable than k=num%10;. (There's more to code formatting than a matter of taste; without spaces you create areas full of characters which are more difficult to parse for our visual system.)

Why are the wrong array values being printed? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
For some reason, the nested for loop I have created at the bottom seems to be printing out the wrong first value (Gives me 3, when it should be 8). Yet, when I simply do printf (at the bottom), I am given the right value. Not really sure what's wrong with my code.
#include <stdio.h>
int main(void)
{
int d;
printf("Please input dimensions: (between 3 and 9, inclusive): \n");
scanf("%i", &d);
int array[d][d];
int k = 1;
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
array[i][j] = (d * d) - k; //d^2 doesn't work to square a function
k++;
}
}
for (int z = 0; z < d; z++)
{
for (int y = 0; y < d; y++)
{
printf("%i\n", array[z][y]);
}
}
printf("%i\n", array[0][0]);
printf("%i\n", array[0][1]);
}
Edit: Sorry guys, the top value that was being printed was my own input. I was simply thinking it was the first value being printed.
Are you sure you aren't looking at your own input? I cut and paste and see:
Please input dimensions: (between 3 and 9, inclusive):
3
8
7
6
5
...
The 3 is actually what I typed and is echoed.

Wrong output for prime numbers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
#include <stdio.h>
int main()
{
int i, n, c, p;
printf("enter\n");
scanf("%d", n);
c = find(n);
if (c == 1)
{
printf("no. is not prime");
}
else
{
printf("no. is prime");
}
}
find(int n)
{
int i = 2, p;
while (i < n)
{
p = n % i;
printf("value of p%d", p);
if (p == 0)
{
return 1;
}
i = i + 1;
}
return 2;
}
....................................
Above program giving me 'not a prime number' output for all inputs...also the value of p is always zero and this shouldn't be the case...
Please help...badly stuck...
Your scanf() call must take the address of n. Furthermore you primality test fails for numbers smaller than 2. It is also better to return non-zero for true, zero otherwise, so that the value can directly be tested with if. And you should find a better name than find.
Try something like this:
#define TRUE 1
#define FALSE 0
int is_prime (int n)
{
int i;
if (n < 2)
return FALSE;
for (i = 2; i < n; i++) {
if (n % i == 0) {
return FALSE;
}
}
return TRUE;
}
int main()
{
int n;
printf ("enter number: ");
scanf ("%d", &n);
if (is_prime (n)) {
printf ("number is prime.\n");
}
else {
printf("number is not prime.\n");
}
return 0;
}
Various improvements are possible but I wanted to stay as close to your code as possible.
This looks like a student exercise so let me start by suggesting that the debugger is your friend. :)
Having said that, you may want to review the Sieve of Eratosthenes and leverage Wikipedia for a source of some good test content.
As already suggested, there are loads of potential improvements... I'd modify your "find" function to be more clear as follows:
bool IsPrime(unsigned int n)
{
unsigned int nCounter = 2;
while (n % nCounter++);
return (nCounter > n);
}
Prime's can't be negative and since you're asking a "TRUE/FALSE" question, the name and return type should enforce that contract.
Several issues:
scanf("%d", n); should be scanf("%d", &n); - you need to pass the address of n so scanf can update it (note that you risk a runtime error,
since the value of n most likely isn't a valid address value);
Implicit typing of functions such as find(int n) {...} is no longer supported as of the C99 standard, and it was never good practice to begin with. You should (and for C99 and later, must) provide a type specifier along with the function name in both function declarations and function definitions - int find( int n ) {...};
Similar to 2, a function declaration must be visible before a function is called; the simplest way to accomplish this is to move the function definition above the definition for main. If you don't want to do that, then you need to add the declaration int find(int n); somewhere before find is called.
Note that you can speed up the primality test in a couple of ways. First, you can skip testing against even factors; if a number is divisible by a multiple of 2, then it's divisible by 2, and you would have already checked for that. Secondly, you don't need to test all factors up to n - 1; you only need to test factors up to the square root of n. You can put that all together like so:
if ( n < 2 )
return 0; // zero indicates false
if ( n == 2 )
return 1; // non-zero indicates true
int result = n % 2;
for ( int i = 3; result && i * i <= n; i += 2 ) // loops as long as result
result = n % i; // is non-zero, only tests
// against odd numbers up to
return result; // sqrt(n)

Resources