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;

scanf("%d", &num1);
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.

## All 3 Replies

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 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.