Search code examples
ccygwin

Simple Printf loop from array


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int
main(int argc,char **argv)
{
    int array[10];

    int count = sizeof(array) / sizeof(int);

    array[0] = 1;

    int index = 1;
    while (index < count)
    {
        array[index] = array[index - 1] * 2;
        index = index + 1;
    }

    while (index < count)
    { 
        printf("%d\n",array[index]);
        index = index + 1;
    }
    return 0;
}

I'm attempting to loop printf statements to save typing time so I won't have to type out the entire thing each time I want to print out a new result. When I run the program as above, nothing prints out.

My question is: how do I loop the printf statements so I don't have to write

printf("%d\n", array[0]); 

etc for each new printf command, if my objective is to print out all 10 values of the array?

Edit: For future viewers, redefine index as 0 before printing out the statement.


Solution

  • The first loop while (index < count) finishes when index == 10.

    So the next loop while (index < count) is never entered because the condition is initially false.

    A tidier way to write the two loops is:

    for ( int index = 1; index < count; ++index )
    {
        array[index] = array[index - 1] * 2;
    }
    
    for ( int index = 0; index < count; ++index )
    {
        printf("%d\n", array[index]);
    }
    

    By scoping the counter variable to the loop like this, you prevent the sort of error that you had in your program.