Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C Program

  1. Mar 7, 2007 #1
    can someone tell me why this program is equal to 9? I have been sitting for 2

    hours trying to figure out how the program gets and when doing it by hand I

    get something different. Here is the program:

    #include <stdio.h>

    int main()
    int i, j;
    int a=0;
    for (i=0;i<3;i++)
    for (j=0;j<2;j++)
    printf("%d\n", a);
    return 0;

  2. jcsd
  3. Mar 7, 2007 #2
    what you mean why?
    i=0, j=0: 2*i+j-1=-1, a=-1
    i=0, j=1: 2*i+j-1=0, a=-1
    i=1, j=0: 2*i+j-1=1, a=0
    i=1, j=1: 2*i+j-1=2, a=2
    i=2, j=0: 2*i+j-1=3, a=5
    i=2, j=1: 2*i+j-1=4, a=9
  4. Mar 7, 2007 #3
    can u explain why you alternated the values in i and j and in what sequence you did it in please?
  5. Mar 7, 2007 #4

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    They represent
    In other words, whatta executed the program by hand.

    Mathematically, your code is calculating

    [tex]a=\sum_{i=0}^2\sum_{j=0}^1 2i+j-1[/tex]

    First evaluate the inner sum (the sum over [itex]j[/itex]). Note that the term [itex]2i-1[/itex] is a constant in this inner sum. Using

    [tex]\sum_{k=0}^n c = (n+1)*c[/tex]

    [tex]\sum_{k=0}^n k = \frac{k*(k+1)}2[/tex]

    The inner sum evaluates to

    [tex]\sum_{j=0}^1 2i+j-1 = 2*(2i-1)+\frac{1*2}2 = 4i-1[/tex]

    The outer sum thus becomes

    [tex]a=\sum_{i=0}^2 4i-1 = 4\frac{2*3}{2}-3*1 = 12-3 = 9[/tex]
  6. Mar 7, 2007 #5
    or, in the rant straight from mighty wikipedia: click
  7. Mar 7, 2007 #6


    User Avatar
    Homework Helper

    Perhaps it makes more sense with while loops:
    Code (Text):

    int main()
        int i, j;
        int a=0;
        i = 0;
        while (i < 3) {
            j = 0;
            while (j < 2) {
                a += 2*i+j-1;
        printf("%d\n", a);
        return 0;
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook