3

i m new in programing. i've written a simple program. i want to repeat the program again and again and it can only exit when user wants to exit. here is my program

#include<stdio.h>
#include<conio.h>
main()
{
    char ch;
    int num1, num2, a, m, s, choice;
    float d;
    printf("\nEnter The First Number: ");
    scanf("%d", &num1);
    printf("\nEnter The Second Number: ");
    scanf("%d", &num2);
    a=num1+num2;
    m=num1*num2;
    s=num1-num2;
    d=(float)(num1/num2);
    printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
    scanf(" %c", &ch);
    switch(ch)
        {
            case 'A': printf("\nThe Addition Of The Number Is= %d", a);
                break;
            case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
                break;
            case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
                break;
            case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
                break;
            default : printf("\nInvalid Entry");
                break;
        }
    printf("\nPress Any Key To Exit");
    getch();
    return 0;
}

and here is the output

"Enter The First Number: 10

Enter The Second Number: 10

Enter Your Choice

For Addition Type A

For Multipication Type M

For Division Type D

For Substraction Type S : A

The Addition Of The Number Is= 20

Press Any Key To Exit"

I want a line before the line Press Any Key To Exit

"If You Want To Calculate Again Press Y

or

Press Any Key To Exit"

when press Y then the program should start from the beginning.

How can i do this???

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
MaxySpark
  • 555
  • 2
  • 10
  • 26
  • Have you heard about [goto](http://www.tutorialspoint.com/cprogramming/c_goto_statement.htm) in `C`? – Jayesh Bhoi Sep 14 '14 at 09:21
  • no. can you explain? plz – MaxySpark Sep 14 '14 at 09:25
  • see the link in my comment. Also `while..loop` is another option. – Jayesh Bhoi Sep 14 '14 at 09:27
  • @Jayesh While goto is a correct solution, I would like to point out the problems it has: https://en.wikipedia.org/wiki/Goto#Criticism – Jens Mühlenhoff Sep 14 '14 at 11:41
  • 1
    @MaxySpark `main()` is not a valid declaration of the main function (according to the C standard), it should be `int main(void)` or `int main(int argc, char* argv[])`. This also goes for C++ (with the minor difference that you don't use `void` as the argument), see this answer: http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main – Jens Mühlenhoff Sep 14 '14 at 11:44
  • @MaxySpark You should be careful with `(float)(num1 / num2)`. When `num2 == 0` this will cause a division by zero error. – Jens Mühlenhoff Sep 14 '14 at 11:46
  • @MaxySpark `conio.h` only works on MS-DOS and Windows, it is a legacy header file. I wouldn't use it. https://en.wikipedia.org/wiki/Conio.h – Jens Mühlenhoff Sep 14 '14 at 11:47
  • @MaxySpark It wouldn't clear the screen at all (that's pointless and only means that the user can't see his previous input, also there is no standard way to clear the "screen"/virtual terminal). You can use `getchar()` (from `stdio.h`) instead of `getch()` (from `conio.h`). – Jens Mühlenhoff Sep 14 '14 at 11:49
  • @Jens Mühlenhoff what will happen if i write 'int main()'. Is it correct for **C**? – MaxySpark Sep 14 '14 at 11:52
  • @MaxySpark It is not correct for `C`, see also here: http://stackoverflow.com/questions/18376783/fvoid-meaning-no-paramters-in-c11-or-c – Jens Mühlenhoff Sep 14 '14 at 12:09
  • @MaxySpark I wrote an answer which tries to address these issues and more. – Jens Mühlenhoff Sep 14 '14 at 12:45
  • The cool way to do this is with recursion. ;) – vek Sep 14 '14 at 13:12

3 Answers3

5

wrap the code inside a do{} while() ?

char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
    {
        case 'A': printf("\nThe Addition Of The Number Is= %d", a);
            break;
        case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
            break;
        case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
            break;
        case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
            break;
        default : printf("\nInvalid Entry");
            break;
    }
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');

Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.

Unix von Bash
  • 735
  • 5
  • 20
  • can you explain how to write the condition after while. please – MaxySpark Sep 14 '14 at 09:37
  • 1
    1) There is no "Do" in C (maybe you meant "do" ?) 2) there should be a semicolon after the while(condition): `while(answer == 'y' || answer == 'Y');` – wildplasser Sep 14 '14 at 09:51
  • @MaxySpark: use clrscr(); See http://priyankmaniar.hubpages.com/hub/Explaining---clrscr--and-getch-in-C – Unix von Bash Sep 14 '14 at 10:10
  • `clrscr()` is a non-standard function, in the non-standard `conio.h` header. There *is* no general way to "clear the screen" in C. One way is to print lots of empty lines (and you don't know how many); another way is to use `ncurses`, which is available for lots of platforms; or find out if the OP's terminal supports Terminal Escape codes, and use those. – Jongware Sep 14 '14 at 11:44
  • @MaxySpark: *that* you should type in Google. – Jongware Sep 14 '14 at 12:30
  • I mean how can i use **ncurses** here? – MaxySpark Sep 14 '14 at 12:40
  • @MaxySpark: not surprisingly, the command is called [`clear()`](http://linux.die.net/man/3/curs_clear). As you are "new in programing", looking up how to install ncurses on your system and then use it is a pretty good exercise. – Jongware Sep 14 '14 at 12:55
2

I would move the calculation stuff in it's own function and then use while() in main.

I have tried to fix other problems as well (this solution only uses standard C functions).

#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper

char fail_on_eof (int c)
{
    if (c == EOF)
        exit (EXIT_FAILURE);
    // In case of fail_on_eof (scanf (...)) the return value of this this
    // function is not useful
    // scanf () returns the number of chars read or EOF
    // getchar () returns a char or EOF
    return (char) c;
}

void skip_to_next_line (void)
{
    char c;
    do
    {
        c = fail_on_eof (getchar ());
    } while (c != '\n');
}

char read_upcase_char_line (char* prompt)
{
    char c;
    printf ("%s ", prompt);
    c = fail_on_eof (toupper (getchar ()));
    skip_to_next_line ();
    return c;
}

int read_num_line (char* prompt)
{
    int num;
    printf ("%s ", prompt);
    fail_on_eof (scanf ("%d", &num));
    skip_to_next_line ();
    return num;
}

int calculate (void)
{
    char choice;
    int num1, num2, cont;
    num1 = read_num_line ("Enter the first number:");
    num2 = read_num_line ("Enter the second number:");
    puts("A - addition");
    puts("S - subtraction");
    puts("M - multiplication");
    puts("D - division");
    choice = read_upcase_char_line ("[ASMD]?");
    puts("");
    switch(choice)
    {
        case 'A':
            printf("%d + %d = %d", num1, num2, num1 + num2);
            break;
        case 'S':
            printf("%d - %d = %d", num1, num2, num1 - num2);
            break;
        case 'M':
            printf("%d * %d = %d", num1, num2, num1 * num2);
            break;
        case 'D':
            if (num2 == 0)
                // Better use stderr for error messages
                fprintf(stderr, "The divisor can not be zero");
            else
            {
                printf("%d / %d = %f", num1, num2, (double)num1 / num2);
            }
            break;
        default :
            // Better use stderr for error messages
            fprintf(stderr, "Invalid entry");
            break;
    }
    printf("\n");
    for (;;)
    {
      cont = read_upcase_char_line ("Continue [YN]?");
      if (cont == 'Y')
          return -1;
      else if (cont == 'N')
          return 0;
    }
}

int main(void)
{
    while (calculate ());
    return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
  • I m new in programming. So i don't know about #include #include #include . Thats why your answer is little bit tough for me. :( – MaxySpark Sep 14 '14 at 12:44
  • @MaxySpark You can look everthing up, for the different headers and there meaning see here for example: https://en.wikipedia.org/wiki/C_standard_library – Jens Mühlenhoff Sep 14 '14 at 12:46
  • @MaxySpark Yes, I put some advanced methods in there, but I would advice you to study this solution as it contains some best practices and avoids some errors. You can ask, if you don't understand something. – Jens Mühlenhoff Sep 14 '14 at 12:47
  • @MaxySpark BTW: `stdbool.h` was uneccessary, I removed it. I also wrote which functions are imported from which headers. Maybe that helps. – Jens Mühlenhoff Sep 14 '14 at 13:05
  • thanx. tell me about **fprintf** **stderr** and **toupper** – MaxySpark Sep 14 '14 at 13:41
  • @MaxySpark There are two default file handles called `stdout` and `stderr`, when you use `printf` the output goes to `stdout`. You can do the same with `fprintf(stdout, ...)`. Both streams are printed to the console by default, but you can redirect them. http://www.cplusplus.com/reference/cstdio/stderr/ – Jens Mühlenhoff Sep 14 '14 at 14:22
  • 1
    @MaxySpark `toupper` will convert lower case characters to upper case characters. So the program can use `a` as well as `A` which is more pleasing for the user. – Jens Mühlenhoff Sep 14 '14 at 14:24
2

You can also use recursion, which is often used in more functional oriented programming languages.

Pseudo-code:

myfunction = do 
    ...
    b <- somethingtodo
    ...
    if b
      then myfunction 
      else return ()

Relative to Jens's solution, it would look like:

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

int main (void)
{
    char choice;
    int num1, num2, cont;
    printf("Enter the first number: ");
    scanf("%d", &num1);
    getchar ();
    printf("Enter the second number: ");
    scanf("%d", &num2);
    getchar ();
    printf("A - addition\n");
    printf("S - subtraction\n");
    printf("M - multiplication\n");
    printf("D - division\n");
    printf("[ASMD]? ");
    choice = (char)toupper(getchar());
    getchar (); 
    printf("\n");
    switch(choice)
    {
        case 'A':
            printf("%d + %d = %d", num1, num2, num1 + num2);
            break;
        case 'S':
            printf("%d - %d = %d", num1, num2, num1 - num2);
            break;
        case 'M':
            printf("%d * %d = %d", num1, num2, num1 * num2);
            break;
        case 'D':
            if (num2 == 0)
                fprintf(stderr, "The divisor can not be zero");
            else
            {
                printf("%d / %d = %f", num1, num2, (double)num1 / num2);
            }
            break;
        default :
            fprintf(stderr, "Invalid entry");
            break;
    }
    printf("\n");
    for (;;)
    {
      printf("Continue [YN]? ");
      cont = toupper(getchar());
      getchar ();
      if (cont == 'Y')
          return main(); // the difference.
      else if (cont == 'N')
          return EXIT_SUCCESS;
    }
}
Community
  • 1
  • 1
vek
  • 1,523
  • 10
  • 18