May 20, 2010

Beginning C++

Two solutions for counting average of x < 100 numbers.
#1
int tab100];
    int n=0;
    int number=0;
    char input[10];

    while (n++ < 100)
    {     
       cout << "Give " << n << " number : ";
       memset(input, 0x00, 10);
       cin.getline(input, 10);
       number = atoi(input);
       if (number > 0)
           tab[n-1] = number;
       else
           break;
    }
    cout << average(tab, n-1) << endl; 
    getch(); 
    return 0;

#2
int main()
{
    const size_t COUNT = 100;
    int tab[COUNT];
    size_t n;   

    cin.tie(&cout);

    for (n = 0; n < COUNT; ++n ) {
        cout << "Give " << n+1 << " number : ";
        cin >> tab[n];

        if (!cin)
            break;
    }

    if (n > 0)
        cout << average(tab, n) << endl;
    
    getch();
    return 0;
}

Which one do you prefer ?

1 comment:

  1. second 1 is shorter, and that was why cpp is so weird - to make ur code shorter.

    ReplyDelete