How to Optimize my first C code?

62 Views Asked by At

I am a beginner, and it is my first program in C. It works good, but I was wondering if there is a shorter way to do it? It supposes to make a quadratic expression and ask the user to factor it. If the user factor it correctly s/he goes to next level, which is a slightly harder question. if s/he cannot solve it correctly she/he stays on the same level, unless s/he wants to exit. Thanks

# include <stdio.h>
# include <stdlib.h>
# include <ctype.h>
# include <string.h>
# include <math.h>
# include <time.h>

int main() {

  srand(time(0));
  int a, b, c, level=1, randMax=level*5;
  char ch;

  // generate the problem to ask
  int ask(){

    // generate non-zero random number for first coefficient
    // that is less than the level of the game, but not zero
    int nonZeroCoefficient(){
      int n = (rand()%(level+2) - (level));
      if ( n == 0 ){
      n++;
      }
      return n;
    }

    // generate non-zero random number

    int nonZeroRand(){
      int n=(rand()%randMax - (randMax));
      if (n == 0){
        n++;
      }
      return n;
    }

    int f = nonZeroCoefficient();
    int h = nonZeroCoefficient();
    int k = nonZeroRand();
    int g = nonZeroRand();

    a = f*h;
    b = (f*k + g*h);
    c = g*k;


    // shows the Level
    printf("\n\n\n\n --- Level %d ---", level);

    // generate the question
    printf("\nfactor the following expression\n%dx^2 %+dx %+d",a ,b, c);
    puts("\n\nEnter your answer in the form of (fX+g)(hX+k)");
    int inputF, inputG, inputH, inputK;
    printf("\nEnter f:");
    scanf("%d", &inputF);
    printf("Enter g:");
    scanf("%d", &inputG);
    printf("Enter h:");
    scanf("%d", &inputH);
    printf("Enter k:");
    scanf("%d", &inputK);

      if (inputF*inputH == a && ((inputF*inputK+inputG*inputH== b) && (inputG*inputK == c))){
        printf("\nRight on!\n");
        level++;

      }else{
        printf("\nSorry! your answer is not currect!\nthe currect answer is:\nf:%d\ng:%d\nh:%d\nk:%d\n \ntry again",f, g, h, k);
      }

    }


    do{
      ask();
      printf("\nDo you want to continue? (Y/N)");
      scanf (" %c", &ch);
    } while(ch == 'y'|| ch == 'Y');

}
0

There are 0 best solutions below