user1800989
user1800989

Reputation:

Why does my code all of a sudden stop here in this C program?

I've written a program where you can select any number and ties it by itself to the power of any number. The code works out ok, until it hits a certain part, where I then have to type in a character to make it move move onto the next part of the code. Here's what I mean:

#include <stdio.h>

int power (int x, int y);

int
power (int x, int y)
{
    int i, b;

    i = 1;
    scanf ("%d", &x);
    scanf ("%d", &y);
    b = x;

    for (i = 1; i < y; i++) {
        x *= b;
    }
    return x;
}

int
main ()
{
    int base, i;

    printf ("Type the base number:  ");
    scanf ("%d", &base);

    printf ("Type the power:  ");
    scanf ("%d", &i);

    int final = power (base, i);

    printf (" The power is %d ", final);

    return 0;
}

So up to int final=power(base,i), everything runs smoothly, however the next part of the code where it prints the answer doesn't actually print. The only way it does print is if i time in any character on my keyboard and then press return, when it should print the moment i press enter after typing in the the amount I want to power my number by. Any suggestions to fixing this glitch, I'm fairly new to c.

Upvotes: 3

Views: 218

Answers (3)

pzn
pzn

Reputation: 141

In your code in function power you call "scanf" twice and these calls and overwrite arguments passed to the function. Remove there "scanf" calls.

If you modify your code in such way, everything will be clear:

int power(int x, int y)
{
        int i,b;
        i=1;

        printf("before scanf no 1\n");
        scanf("%d",&x);
        printf("before scanf no 2\n");
        scanf("%d",&y);
        b=x;

        for(i=1;i<y;i++)
        {
                x*=b;

        }
        return x;
}

Upvotes: 0

wjmolina
wjmolina

Reputation: 2675

Remove scanf("%d",&x); and scanf("%d",&y); in power; you already passed x and y to power as arguments in main.

Upvotes: 8

your power function has scanfs in it. it's waiting for user input.

scanf("%d",&x);
scanf("%d",&y);

it essentially means fill x and y with numbers that you type.

scanf documentation

Upvotes: 3

Related Questions