Logical Error

This is a discussion on Logical Error within the C Programming forums, part of the General Programming Boards category; I have a logical problem that i want to divide any number by 2. i.e 4/2 the answer is 2 ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    12

    Logical Error

    I have a logical problem that i want to divide any number by 2. i.e 4/2 the answer is 2 & the remaining is Zero. If i divide 5/2 then the remaining woule be 1.
    My problem is that either i input 4 or 5 value in num the ELSE statement always execute. There is a logical error in my coding. I want that if i divide 4/2 then the remainder is Zero so the statement after if should be executed other wise the else statement but here always my else statement execute.
    Please help how can i solve my Logical error. Thanks in Advance...

    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int num,div;
    clrscr();
    printf("\n\tEnter any value = ");
    scanf("%d",&num);
    div=num/2;
    if (div==0)
    printf("\n\tRemaining is zero");
    else
    printf("\n\tRemaining is One");

    getch();

    }

  2. #2
    Registered User
    Join Date
    Mar 2003
    Location
    UK
    Posts
    169
    Use the modulus operator % to find the remainder.
    Code:
    div = num % 2;

  3. #3
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    The only way that the statement
    Code:
     div=num/2;
    will evaluate to 0 is if num==0. Scarlet7 was right, replace that line with
    Code:
    div=num%2;
    You might also want to change the name of "div" to something like "remainder." Or you could streamline the code a bit

    Code:
    if (num%2)
         printf("\n\tRemaining is one");
    else
         printf("\n\tRemaining is zero");
    That works because false is the same as 0 and true is anything else.
    Away.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 02:01 AM
  2. Making C DLL using MSVC++ 2005
    By chico1st in forum C Programming
    Replies: 26
    Last Post: 05-28-2008, 02:17 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 09:39 AM
  4. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 04:49 AM
  5. Couple C questions :)
    By Divx in forum C Programming
    Replies: 5
    Last Post: 01-28-2003, 01:10 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21