1

I am new to C (and programming in general, minus a few weeks with Python). I am interested in learning how information is handled on a machine level, therefore I moved to C. Currently, I am working through some simple coding challenges and am having trouble finding information to resolve my current issue.

The challenge is to take N large integers into an array from input and print the sum of the numbers. The transition from Python to C has actually been more difficult than I expected due to the simplified nature of Python code.

Example input for the code below:

5
1000000001 1000000002 1000000003 1000000004 1000000005

Expected output:

5000000015

Code:

int main() {
    long long unsigned int sum = 0;
    int nums[200], n, i;
    scanf("%i", &n);
    for (i = 0; i =! n; i++) {
        scanf("%i", &nums[i]);
        sum = sum + nums[i];
    }
    printf("%llu", sum);
    return 0;
}

The program seems to accept input for N, but it stops there.

One last question, in simple terms, what is the difference between a signed and unsigned variable?

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
JG7
  • 371
  • 2
  • 10
  • 2
    `=!` probably isn't what you are looking for (you could use it to assign the NOT of a value to another variable). If you are looking for `not ==` then use `!=` – Arc676 Nov 19 '15 at 14:46
  • =! in the for loop is incorrect. i < n is more appropriate (or use !=). The difference between a signed and unsigned variable is that the Most significant bit is used as a sign (+, -) in signed variables. – Shyamal Desai Nov 19 '15 at 14:53
  • [Signed versus Unsigned Integers](http://stackoverflow.com/questions/247873/signed-versus-unsigned-integers) – 001 Nov 19 '15 at 14:57
  • "I am interested in learning how information is handled on a machine level, therefore I moved to C." - bear in mind that C gets you clos**er** to the machine level than Python, but it's still pretty far removed. C's data types and operations are *abstractions* of the types and operations provided by most hardware. If you *really* want to dig into machine-level details, you will need to learn assembler at some point. – John Bode Nov 19 '15 at 15:20

1 Answers1

4

Change your for loop like this

for (i = 0; i != n; i++) {
    scanf("%i", &nums[i]);
    sum = sum + nums[i];
}

if you say i =! n that is the same as i = !n. What that does is to assign the negated value of n to i. Since you gave a non-zero value to n the result is zero and the loop terminates.

Welcome to C!

Regarding the signed vs unsigned question. signed types can have negative values and unsigned can't. But they both take up the same space (number of bits) in memory. For instance, assuming twos' complement representation and a 32 bit integer, the range of values is

singed   : -2^31 to 2^31 - 1  or  –2147483648 to 2147483647
unsigned :     0 to 2^32 - 1  or            0 to 4294967295
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82