Pointer Variable in a Loop

Good Morning! I am having problems writing a program. This is my assignment:

******************************************************
Write a program to declare and initialize the following array:

int number[] = {0,1,2,3,4,5,6,7,8,9};

The program should use a pointer variable in the loop to print the value of each element, one value per line of output. Use the sizeof() function to determine the array size to control your loop.

*******************************************************

Here is my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
//#include <stdio.h>

using namespace std;

int main()


{
    int i = 0;
    //create an array

    int number [] = {0,1,2,3,4,5,6,7,8,9};

    //get the size of numbers

    int count = sizeof(number) / sizeof(number+1);

    //set up pointer

    int *num = number;

    //using pointers


    for (i = 0; i < count; i++)

        //{
        //printf(*num+i);
        //}



return 0;

}


I commented out lines 2 and 28-30 because I was getting error messages. When i run the program now, it runs but nothing shows. How do I get the array to print to the screen?
Have you ever used cout?
Including stdio.h should be fine.

Printf requires a format string. You can fix it like this:
printf("%d", *num+i);
The %d will be replaced with the value of *num+i.

Edit: Like Peter87 said, you can use cout.

1
2
3
4
5
// At top of file instead of stdio.h:
#include <iostream>

// And instead of printf:
cout << *num+i;
Last edited on
@Peter87- Yes, I have. I was getting myself all confused.
Last edited on
@programmerdog297- Thank YOU! That fixed it:)
how do I get each number to print on a separate line? do I use /n somewhere?
You can use \n.
printf("%d\n", *num+i);
That did it! For anyone interested, the final and working code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <stdio.h>

using namespace std;

int main()

{
    int i = 0;

    //create an array

    int number [] = {0,1,2,3,4,5,6,7,8,9};

    //get the size of numbers

    int count = sizeof(number) / sizeof(number+1);

    //set up pointer

    int *num = number;

    //using pointers


    for (i = 0; i < count; i++)

        {
        printf("%d\n", *num+i);
        }

return 0;

}
Topic archived. No new replies allowed.