Collecting array entries and displaying it like its formal representation
Taking array entries from the user and displaying it like its formal representation as {1,2,..5}
Learning Objectives
- Collecting all entries of an array from the user.
- Defining size of array using the pre-processor define macros.
- Trick of not printing last comma when printing comma separated array members.
- Neat printing of array like a real array representation.
Source Code
|
Run Output
Code Understanding
#define asize 5
This is an easy technique to define the array size outside the main, so that the word asize can be replaced by 5 everywhere the compiler finds it. This most common use of preprocessor macros.
int a[asize]; //This will be read as compiler as int a[5]; defining an array which can take 5 integer members.
int cnt=asize; //This will be taken as int cnt=5; It will make it easy for programmer to use the size variable everywhere else in the program.
for(int i=0;i<cnt;++i) //This loop run from 0 to <4 means 5 iterations will happen in this case.
{
cout<<“Enter member “<<i+1<<” : “; cin>>a[i];
Here we collect each member of array. Since array index starts from 0 and array position as known to real world begins from 1 so we write i+1, so that user can be shown which position he is entering the member for.
}
cout<<endl<<“The array you entered is :”<<endl; //This is prompt before array display
cout<<‘{‘; //To show the real array like display we begin it by printing { . We print it before the array printing loop as it has to be printed just once.
for(int i=0;i<cnt;++i) //This is array printing loop
{
cout<<a[i]<<((i<=cnt-2)?”,”:””);
Here we print the array member followed by a , (comma). Since the last member will not have a leading comma we will use the ternary expression to achieve this goal. In ternary expression we print comma till we are printing last but one member. This is why we subtract 2 from cnt to determine the last but one member. Up to pre-last member the expression (i<=cnt-2) is true so we print “,” and later when it is false we just do not print anything so “” has been used.
}
cout<<‘}’; //This is final curly braces of the array to be printed.
}
Notes
- Array entries are often collected from the user so that the data can be first stored in memory locations and then final processing can be done on it later.
Common Errors
- If students are committing repeated mistakes in printing it in the right format. They must first try to print array members with leading spaces only. Later they can refer to a similar example at #2042 or they can learn more about this concept at #1728 .
Suggested Filename(s): arr-inp-disp.cpp
sunmitra| Created: 12-Jan-2018 | Updated: 12-Jan-2018|