codescracker
c++

C++ Program on One Dimensional Array



« Previous Program Next Program »

In this article, you will learn and get code on one-dimensional (1D) array in C++. For example:

int arr[5] = {10, 20, 30, 40, 50};

Note - Array such type of variable that can hold upto many values of same type. Same type means, whatever the variable's (array's variable) type was declared. For example, in above array, arr can hold upto 5 integer values.

From above declaration, all the 5 integer values are stored in arr[] in following way:

Note - Here 0, 1, 2, 3, 4 are called as array's index. Indexing in array always starts with 0.

One Dimensional Array Program in C++

To print one dimensional array in C++ programming, you have to ask from user to enter the size and elements of array. Then print it back on output with all its detail as shown in the program given below:

// C++ Simple One Dimensional Array Program
// ----codescracker.com----

#include<iostream>
using namespace std;
int main()
{
    int arr[50], tot, i;
    cout<<"Enter the Size: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Numbers: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    cout<<"\nArray with Index\tIts Value\n";
    for(i=0; i<tot; i++)
        cout<<"arr["<<i<<"]"<<"\t\t\t"<<arr[i]<<endl;
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

C++ program one dimensional array

Now supply inputs say 10 as size and 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 as its elements or numbers to store. Here is the sample run with exactly these inputs:

one dimensional array program in c++

In above program, the following statement:

cout<<"arr["<<i<<"]"<<"\t\t\t"<<arr[i]<<endl;

If we break the things from above statement and divide into static and dynamic output (print), here are the list:

Note - Here dynamic output means, the output gets changed with change in value of i and arr[i]. Things inside "" is considered as static output

Previous array is of type int (integer). Therefore that array can hold upto 50 integer values with same variable arr[] just by changing its index. Now let's try array with its type as char (character) to store characters.

// C++ Program on One Dimensional Array
// ----codescracker.com----

#include<iostream>
using namespace std;
int main()
{
    char str[50];
    int i=0;
    cout<<"Enter First Your Name: ";
    cin>>str;
    cout<<"\nArray Index\t\tIts Value\n";
    while(str[i])
    {
        cout<<"str["<<i<<"]"<<"\t\t\t"<<str[i]<<endl;
        i++;
    }
    cout<<endl;
    return 0;
}

Here is its sample run with user input, codescracker:

c++ single dimensional array program

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker