c/c++ programming

This is a discussion on c/c++ programming within the C++ Programming forums, part of the General Programming Boards category; hello guys, here is my problem #include<stdio.h> main() { int a=2; int b=9; int c=1; while(b) { if(odd(b)) c=c*a; a=a*a; ...

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    17

    Lightbulb c/c++ programming

    hello guys,
    here is my problem

    #include<stdio.h>
    main()
    {
    int a=2;
    int b=9;
    int c=1;
    while(b)
    {
    if(odd(b))
    c=c*a;
    a=a*a;
    b=b/2;
    }
    printf("%d\n",c);
    }

    How many times is c=c*a calculated?
    srinu

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    8
    Looks like C will be calculated twice. Since B is an int, and the assignment b=b/2 when b is origially 9 will result in 4.5, but because b is an int, the .5 is dropped off, and b is 4. And since 9 is odd, C is calculated and assigned. When b is 4, b is true and the while loop executes. It is not odd, however and does not caluclate C. When b=4/2, b is true, and b=2, which is even, thus C not calculated. After that b=2/2, b=1, which is true, and the while loop executes and since it 1 is odd, C is calculated again. Then b=1/2=.5, but just as was the case when b=9/2, b=4.5, the decimal part of an integer gets chopped off, and rounded downward. When b=1/2, it is rounded to 0 and this the while loop terminates. Hope this one helped.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21