Search code examples
crecursionsystempause

'system' was not declared in this scope error


So i dont get this error in other programs but i did get it in this.

This program is an example where i dont get the error.

#include<stdio.h>

int main() {



    system("pause");
} // end main

but in this program below i get the error

#include <stdio.h>
//#include <stdlib.h>

// Takes the number from function1, calculates the result and returns recursively.
int topla (int n) {
    if(n == 1)
    return 3;
    else
        return topla(n-1) + topla(n-1) + topla(n-1);
}

// Takes a number from main and calls function topla to find out what is 3 to the
// power of n 
int function1(int n) {
    return topla(n);
}

int main() {
    int n; // We us this to calculate 3 to the power of n

    printf("Enter a number n to find what 3 to the power n is: ");
    scanf("%d", &n);
    function1(n);

    system("pause");
} // end main

Solution

  • Just include stdlib.h, but don't use system("pause") as it's not standard and will not work on every system, just a simple getchar() (or a loop involving getchar() since you've used scanf()) should do the trick.

    And normally system("pause") is found in windows command line programs because windows command prompt closes when the program exits, so maybe running the program from the command prompt directly would help, or using an IDE that fixes this like geany.

    Finally always check the return value if scanf() instead of assuming that it worked.

    Note: This code

    return topla(n - 1) + topla(n - 1) + topla(n - 1)
    

    you can write as

    return 3 * topla(n - 1);
    

    instead of calling topla() recursively 3 times.

    And you don't really need the else because the function returns unless the n != 1 so even without the else the recursion will stop when n == 1.