0

This code wont doest display the answer why???/

#include <stdio.h>
#include <conio.h>




void main()



    {



      int opcode;

      int num[2];

      int result;

      clrscr();

      printf("Program for Addition, Subtraction, Multiplication and Division\n");

      printf("Enter First Number:");

      scanf("%d", &num[1]);

      printf("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: ");

      scanf("%d", &opcode);

      printf("Enter Second Number:");

      scanf("%d", &num[2]);



      switch(opcode)

      {

      case 1:

        result = num[1] + num[2];

        printf("%d + %d = %d", num[1], num[2], result);

        break;

      case 2:

        result = num[1] - num[2];

        printf("%d - %d = %d", num[1], num[2], result);

        break;

      case 3:

        result = num[1] * num[2];

        printf("%d * %d = %d", num[1], num[2], result);

        break;

      case 4:

        result = num[1] / num[2];

        printf("%d / %d = %d\n%d %% %d = %d", num[1], num[2], result, num[1], num[2], num[1] % num[2]);

        break;

      }

getch();


    }

Edited by Dani: Formatting fixed

2
Contributors
2
Replies
17
Views
3 Years
Discussion Span
Last Post by Decode098
0

You're accessing your arrays incorrectly. When you have an array declared as int num[2], num[0] is your first element and num[1] is your second element. You're passing values of &num[1] and &num[2] to the scanf() function.

As a result, when you think you're entering your first number, you're actually entering the second number. When you think you're entering your second number, you're writing to something beyond the edges of the array and are probably overwritting opcode as a result. If this gets overwritten to something outside of the range of 1 through 4, no answer will be displayed on your screen.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.