Thread: I can't calculate difference between two characters

  1. #1
    Registered User
    Join Date
    Apr 2018
    Posts
    43

    I can't calculate difference between two characters

    Hi guys we got a homework assignment. We have to convert if statements that have "!=" in them to branch zero(==0) or branch positive(>0).

    However the code generates weird input when I do that.
    Could someone tell me what I am doing wrong?


    original code:




    Code:
    #include <stdio.h>
    
    int ch, spaces = 0;
    int diff;
    
    int main(void) {
    
    
    while( (ch = getchar()) != EOF) {
        if( ch == ' ') {
    
            if( ++spaces == 3) {
    
                putchar('*');
    
                spaces = 0;
            }
    
        } 
        if(ch!=' ') {
    
            for( int i=0; i<spaces; i++) 
            putchar(' ');
            spaces = 0;
            putchar(ch);
        }
    }
    
    return 0;
    }

    edited code:

    Code:
    #include <stdio.h>
    
    int ch, spaces = 0;
    int diff;    //to calculate difference for if-statements
    
    int main(void) {
    
    
    while( (ch = getchar()) != EOF) {
        if( ch == ' ') {
            if( ++spaces == 3)
             {
                putchar('*');
    
                spaces = 0;
            }
    
        }
         diff = ch-' ';
         if(diff==0) {
            for( int i=0; i<spaces; i++) 
            putchar(' ');
            spaces = 0;
            putchar(ch);
        }
    }
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Also posted here.

  3. #3
    Registered User
    Join Date
    Apr 2017
    Location
    Quetzaltenango
    Posts
    82
    else or continue

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trying to calculate GPA
    By avavida in forum General Discussions
    Replies: 1
    Last Post: 05-21-2017, 12:33 PM
  2. Calculate E
    By hyper nova in forum C Programming
    Replies: 4
    Last Post: 03-10-2016, 07:25 AM
  3. calculate time difference
    By ak47 in forum C Programming
    Replies: 4
    Last Post: 07-16-2015, 10:51 AM
  4. Program to calculate difference in time.
    By zaiken in forum C Programming
    Replies: 3
    Last Post: 11-08-2014, 04:14 PM
  5. Calculate BMI and BMR
    By nguystep in forum C Programming
    Replies: 4
    Last Post: 10-26-2011, 02:59 AM

Tags for this Thread