Hi,

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");
    scanf("%d",&count);
    printf("Now second number:\n");
    scanf("%d", &n);
    sum=0;


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

/* vahid.a1996@gmail.com */

code no2:

#include<stdio.h>

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);

    while(count<=num1)
    {
        sum = sum + num1;
        ++num1;
    }

    printf("is %d", sum);

    return 0;
}

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....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.