This two parts of code both are intended to do one thing. get two numbers from user, calculate sum between them. print it.

now only the first code is working properly. second one is faulty. but why? what's the problem?

code no1:

#include <stdio.h>
int main()
    int n, count, sum;
    printf("Enter first number:\n");
    printf("Now second number:\n");
    scanf("%d", &n);

    if (n<0 || count<0)
        puts("ERROR!!!\nCan't be negative!\n\n");
    printf("Sum = %d",sum);
    return 0;

/* vahid.a1996@gmail.com */

code no2:


int main()
    int num1, count, sum = 0;

    printf("Please enter two numbers:\n");
    scanf("%d", &num1);
    printf("Please enter two numbers:\n");
    scanf("%d", &count);

        sum = sum + num1;

    printf("is %d", sum);

    return 0;

Edited 1 Year Ago by Vahid_1

How is the second one faulty? The most notable potential problem is you're incrementing num1 rather than count, but whether that's a bug depends on what you expected to happen.

Just compiled it with count being incremented instead of num1. if I enter 5 as num1 and 1 as count it gives me 25 which is wrong.

funny. I wrote first code a week ago and second one today.

base on the second code (you said you have change ++num1, to ++count) and the value of num1 = 5 and count=1, you have sum = sum+num1, which is
0 + 5 = 5;
5+ 5 = 10, count = 2
10 + 5 = 15, count = 3
15 + 5 = 20, count = 5
20 +5 = 25, count = 5, which is also equal num1, i.e num1 = 5, from the beginning ..the while loop will terminate here.. so it is not wrong, it depend on what you will like to do....

Edited 1 Year Ago by jnneson

This article has been dead for over six months. Start a new discussion instead.