Search code examples
c

How to loop back to main after executing a function in C


I want to loop back to the main function in my program but I can't simply call it again in another function due to main being undeclared in the part of the code where the other functions are, is there a way I can fix this?

#include <stdio.h>
#include <conio.h>
#include <cbm.h>
int integer1;
int integer2;
int integer3;
int option;
char choice;

void addition (){
  integer3 = integer1 + integer2;
  printf("%d\n", integer3);
  integer1 = 0;
  integer2 = 0;
  integer3 = 0;
  main();
}

void subtraction (){
  integer3 = integer1 - integer2;
  printf("%d\n", integer3);
  integer1 = 0;
  integer2 = 0;
  integer3 = 0;
  main();
}

void multiplication (){
  integer3 = integer1 * integer2;
  printf("%d\n", integer3);
  integer1 = 0;
  integer2 = 0;
  integer3 = 0;
  main();
}

void division (){
  integer3 = integer1 / integer2;
  printf("%d\n", integer3);
  integer1 = 0;
  integer2 = 0;
  integer3 = 0;
  main();
}

int main()
{ 
   printf("ADVANCED CALCULATOR VERSION 0.2\n");
   printf("CALCULATOR OPTIONS ARE:\n");
   printf("1. ADDITION\n");
   printf("2. SUBTRACTION\n");
   printf("3. MULTIPLICATION\n");
   printf("4. DIVISION\n");
   printf("5. ADVANCED OPERATIONS\n");
   printf("PLEASE SELECT YOUR OPTION.\n");
   scanf("%d", &option);
   if (option == 1){
      printf("FIRST NUMBER?\n");
      scanf("%d", &integer1);
      printf("SECOND NUMBER?\n");
      scanf("%d", &integer2);
      addition();
      }
      else if (option == 2){
        printf("FIRST NUMBER?\n");
        scanf("%d", &integer1);
        printf("SECOND NUMBER?\n");
        scanf("%d", &integer2);
        subtraction();
      }
      else if (option == 3){
        printf("FIRST NUMBER?\n");
        scanf("%d", &integer1);
        printf("SECOND NUMBER?\n");
        scanf("%d", &integer2);
        multiplication();
      }
      else if (option == 4){
        printf("FIRST NUMBER?\n");
        scanf("%d", &integer1);
        printf("SECOND NUMBER?\n");
        scanf("%d", &integer2);
        division();
      }
      else {
        printf("Bruh");
        //exit();
         }
}

I have tried to solve this issue on my own but I could not really find anything good (and possibly understand anything I found since I'm new to C). I would put the main statement first but then that would just cause the other functions to not be declared. Any advice would help, thanks!


Solution

  • Use a while loop

    Put a while loop in your main

    int main()
    { 
      while(true)
      {
        ...
      }
      return 0;
    )
    

    and remove the calls to main()