Code About Us Tutorial


  Arrays
    What is an Array?
    Array Elements
    Filling an Array
    Initializing An Array
    Multidimensional Arrays


   
 

Home > Arrays > Filling an Array

November 28, 2009 4:26 pm

   

Filling an Array

 

 
#include <iostream.h> 

int main() { int anArray[5]; int i;

cout <<"Enter 5 numbers to fill the array."; for(i = 0; i < 5; i++) { cout << “anArray[“ << i << “]” << “n”; cin >> anArray[i]; }

for(i = 0; i < 5; i++) { cout <<"Here are the numbers in the array. cout <<"anArray[" << i << "]" << anArray[i] << "n";

} return 0;

}

In this example, I created an array that stored 5 integer elements. I created a for loop to allow the user to enter 5 numbers into the array. The second for loop I created was to display the contents of the array. The cin >> anArray[i]; is where the array got filled each time the for statement loops.

(The array looks like this if you entered these 5 numbers: 4, 5, 7, 30, and 40. )

anArray Numbers You Entered:
4 5 7 30 40
0 1 2 3 4

(This shows the values you entered on top, and the index values on the bottom of the table.) Please Rate this Code:


    Comments for: Filling an Array
Annonymouse User says:
this code is very vague? How is a user suppose to know what numbers they are allowed to enter? float or integer? there is not message on the program \"PLEASE ENTER 5 NUMBER\"? user does not know how many numbers they are allowed to enter?. i feel this is a bad example of ARRAY

Annonymouse User says:
this code is very vague? How is a user suppose to know what numbers they are allowed to enter? float or integer? there is not message on the program \"PLEASE ENTER 5 NUMBER\"? user does not know how many numbers they are allowed to enter?. i feel this is a bad example of ARRAY says:
how do you fill an array with character using cin.getline

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
 
 
char mystring[30] = {0}; // Initialize to 0
cin.getline (mystring, 30);

Thats all.

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
 
 
char mystring[30] = {0}; // Initialize to 0
cin.getline (mystring, 30);

Thats all. says:
Enter 5 numbers to fill the array

not vague





Add Comment:
Name:
Email:


 «11» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.