Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

My Program stalls before giving output, While loop (Learning C as a first language)

Anjan SriAnjan Sri Member Posts: 2

hey all, I've written a simple program that adds the nth power of numbers, (I hope the comments are clear enough).
The code itself works, just there is one glitch, whenever the program calculates the sum, instead of displaying output immediately, it stalls, then if i type any random character and press the return key it displays the output. I am not using any sort of getchar thing to do that.
Here is the code

include <stdio.h>

include <math.h>

int main()
{
//while first checks the given condition. if it is true, the code is
//executed. this loop goes on till the test condition is made true

long long reqd_index;
unsigned long long exponent, exponent_sum = 0;
int c = 0, exponent_power;
const int b =1;

printf("The number you wish to find the nth power sum of is : ");

//sum of terms from 1 till input number all raised to some power n
//in pattern 1 + 2^x + 3^x .... n^x

scanf("%lld", &reqd_index);
printf("Please enter the power of terms to be added : ");
scanf("%d \n", &exponent_power);

while(c != reqd_index)
{
c += b;
exponent = pow(c, exponent_power);
exponent_sum += exponent;
}

printf("The exponent_sum = %llu \n", exponent_sum);
return 0;
}

for the same code, if I replace exponent_power, with a static number, no stalling occurs. can someone help me understand why this happens?

Answers

  • Anjan SriAnjan Sri Member Posts: 2

    oh, and if it helps, I'm using the gcc compiler on linux

  • Tyson BlairTyson Blair Member Posts: 35
    while(c != reqd_index)
    {
    c += b;
    exponent = pow(c, exponent_power);
    exponent_sum += exponent;
    }
    

    This looks like the problem it should be

    while(c != reqd_index)
    {
    c += b;
    exponent = pow(c, exponent_power);
    exponent_sum += exponent;
    printf("The exponent_sum = %llu \n", exponent_sum);
    }
    
  • Tyson BlairTyson Blair Member Posts: 35

    Hum, Just tested it and has same problem. This is strange.

Sign In or Register to comment.