for loop elements to array

hey all, just a quick question. how exactly do i add elements from a for loop to an array?
That doesn't sound very clear, perhaps you might explain what problem you are trying to solve. Or show the code you have so far and where you are getting stuck.
let's say i have a for loop: for(int i=1;i<=5;i++). and i want to add 1,2,3,4,5 to an array, let's say int Arr[4]. how do i go about doing that? i have some failed attempts, most of the time i get a random number when i print the array
Indexing starts from 0.

1
2
3
int Arr[4];
for (int i = 0; i < 5; i++) // indexing starts from 0 and ends with 4
   Arr[i] = i + 1;

Elements: 1, 2, 3, 4

http://www.cplusplus.com/doc/tutorial/arrays/
http://www.tutorialspoint.com/cplusplus/cpp_arrays.htm
Last edited on
To give you and idea on how to add the elements manually into an array by using the for loop.

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
37
38
39
40
41
42
43
44
#include <iostream>

//Function Prototypes.
void InputIntoArray(int[], int);
void OutputFromArray(int[], int);

int main()
{
    const int SIZE{ 5 }; //Declare and define the size of the array.
    int ArrNum[SIZE]{0}; //Declare and define the values into the array, which is zero.

    InputIntoArray(ArrNum, SIZE); //Call the first function to ask the user to input the integers.
    OutputFromArray(ArrNum, SIZE); //Call the first function to ask the user to output the integers.

    return 0;
}

//This function runs a for loop in accordance
//with the size of the array (variable :sz)
//to obtain the input from the user.
void InputIntoArray(int arrayNumber[], int sz)
{
    std::cout << "Input an integer number " << sz << " times.\n";
    for (int count = 0; count < sz; count++)
    {
	   std::cout << "Number " << count + 1 << ": ";
	   std::cin >> arrayNumber[count];

    }
}
//This function runs a for loop in accordance
//with the size of the array (variable :sz)
//to obtain the output from the user.
void OutputFromArray(int arrayNumber[], int sz)
{
    std::cout << "Outputting the numbers you inputted...\n";
    for (int count = 0; count < sz; count++)
    {
	   std::cout << "Number " << count + 1 << ": ";
	   std::cout << arrayNumber[count];
	   std::cout << std::endl;

    }
}
that helps, thanks!
Topic archived. No new replies allowed.