0

In the Lecture 2 Short on Arrays, Doug Lloyd suggests that it would be a good practice problem to try to output each element of a 100-element array as an integer corresponding to its index position.

Any thoughts as to if I'm on the right track here and what to change? As it is, I keep getting 100 zeros as my output ha.

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int array[100];

    // ?? HOW do I get it to output each int in the array to match its index position, using a loop?
    for (int i = 0; i < 100; i++)
    {
        int x = array[i];

        // Why does this not work??
        printf("%i\n", x);
    }
}

2 Answers 2

0

It's actually working perfectly. It's printing out exactly the contents of the array.

Since the array wasn't initialized with anything, it's using defaults of 0 in every array position. If you had put values into the array, you'd see something different.

Other than that, the code is doing exactly what you want.

If you altered the printf statement a little, you'd see something different. Try this:

    printf("array[%i]: %i\n", i, x);

[edit] If you really want to see it, try this:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int array[100];
    // initialize the array
    for (int i = 0; i < 100; i++)
    {
        array[i] = 200 + i;
    }

    // now, print out the array contents
    for (int i = 0; i < 100; i++)
    {
        printf("array[%i]: %i\n", i, array[i]);
    }
}

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Yes! This was super helpful. Nov 2, 2022 at 18:04
  • I was also able to tweak it and get the same result: Nov 2, 2022 at 18:04
0

This version worked, sort of... but needs tweaking

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int array[100];

    // Per Cliff B, initialize the array with a for loop:
    for (int i = 0; i < 100; i++)
    {
        // INITIALIZATION: This step assigns the value of i (which will increment) to its corresponding index position in the array
        array[i] = i;

        // Suggestion from Cliff B: show yourself each iteration with printf:
        printf("array[%i]: %i\n", i, i);
    }
}
3
  • Not quite. That printf statement just prints the value of i twice. It doesn't print array[i]. That's why I started the initialization in my code with 200 - to show a distinctly different number.
    – Cliff B
    Nov 2, 2022 at 19:43
  • Ok, thanks, I will play with that a bit more Nov 2, 2022 at 20:43
  • I think part of my problem as someone new to coding is that I was mixing up the i used in the for loop iterations with the %i instruction to print an integer. Dumb mistake! But I also did need the tip on how to initialize the array. I appreciate the help! Nov 3, 2022 at 11:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .