113: ***(Syntax)*** Arrays

Arrays

Array is a data structure that can hold multiple values.

  • These values are accessed by index numbers.
  • "Array is like a variable that can hold multiple values", actually array is much more complicated than this but this is a good way of thinking.


1. Making a variable array:
            To make a variable array, add  [] after the variable and then close the values in a set of {} and inside {}  separate each value by , .

Now car is now an array that can hold multiple values ie multiple cars.

#include <iostream>
using namespace std;
int main()
{
    string car[] = {"Corvette", "Ferrari", "Honda"};
   
    return 0;
}


2. Output:
            Now if you output car variable, it will show its memory address where all the values are stored.

#include <iostream>
using namespace std;

int main()
{
    string car[] = {"Corvette", "Ferrari", "Honda"};
    cout << car;
    return 0;
}

The output will be like 0x61fcd0 which is the memory address of car variable.
Now if you want to output the elements in the car, you can do:

#include <iostream>
using namespace std;
int main()
{
    string car[] = {"Corvette", "Ferrari", "Honda"};
    cout << car[0] << endl;
    cout << car[1] << endl;
    cout << car[2] << endl;
    return 0;
}

ie pass index number between [] 


3: Reassigning value:
                You can reassign value to an array and even on the selective index by a statement like: car[1] = {"Mustang"}; where you have changed Ferrari at index 1 to Mustang.

#include <iostream>
using namespace std;
int main()
{
    string car[] = {"Corvette", "Ferrari", "Honda"};
    car[1] = {"Mustang"};
    cout << car[0] << endl;
    cout << car[1] << endl;
    cout << car[2] << endl;
    return 0;
}


4: Same datatype:
            You can only add the values of the same datatype within an array ie you cannot add a number within a string datatype array. Like: string car[] = {"Corvette", "Ferrari", 1}; is wrong because 1 is int within the string car[] .


5: Just Declare, add values after:
            To do this, when you have declared an array, you will also have to give it a size by adding a number between [] (you can skip this step if you are declaring and assigning values at the same time but if you are declaring first and assigning after, you must give it size).

#include <iostream>
using namespace std;
int main()
{
    string car[2];
    // string car[]; is wrong but string car[] = {"Corvette", "Mustang"}; is right
    car[0] = {"Corvette"};
    car[1] = {"Mustang"};
    car[2] = {"Honda"};

    cout << car[0] << endl;
    cout << car[1] << endl;
    cout << car[2] << endl;
    return 0;
}


#include <iostream>
using namespace std;
int main()
{
    float prices[4];

    prices[0] = 53.33;
    prices[1] = 34.55;
    prices[2] = 99.7;
    prices[3] = 23.4;

    cout << "The price of first item is: $" << prices[0] << endl;
    cout << "The price of second item is: $" << prices[1] << endl;
    cout << "The price of third item is: $" << prices[2] << endl;
    cout << "The price of fourth item is: $" << prices[3] << endl;

    return 0;sizeof()
}


6: sizeof() operator:
             sizeof() operator is used to calculate the size of a variable, datatype, class, or object. For this, you just have to place that datatype or variable into () of sizeof() operator.

#include <iostream>
using namespace std;
int main()
{
    int num = 5;
    float num2 = 25.5;
    char alpha = 'd';
    double price = 5.554335;
    string address = "Shalimar Link Road Lahore";
    // array:
    double prices[4] = {53.33, 34.55, 99.7, 23.4};

    cout << sizeof(int) << " bytes" << endl;            // 4 bytes
    cout << sizeof(num) << " bytes" << endl << endl;    // 4 bytes

    cout << sizeof(float) << " bytes" << endl;          // 4 bytes
    cout << sizeof(num2) << " bytes" << endl << endl;   // 4 bytes

    cout << sizeof(char) << " bytes" << endl;           // 1 byte
    cout << sizeof(alpha) << " bytes" << endl << endl;  // 1 byte

    cout << sizeof(double) << " bytes" << endl;         // 8 bytes
    cout << sizeof(price) << " bytes" << endl << endl;  // 8 bytes
   
    cout << sizeof(string) << " bytes" << endl;             // 32 bytes (This will remain 32 because this only hold memory address)
    cout << sizeof(address) << " bytes" << endl << endl;    // 32 bytes
   
    cout << sizeof(prices) << " bytes" << endl;             // 32 bytes (size of whole array combined)
    cout << sizeof(prices[2]) << " bytes" << endl << endl;  // 8 bytes (size of one element)
   
    return 0;
}


Applications of sizeof() operator:

    1. Calculating the number of elements in array:
                You can calculate the number of elements in an array, by dividing the size of that array either by one of its elements ie sizeof(prices) / sizeof(prices[1]) or by the datatype of its elements ie sizeof(prices) / sizeof(double).

#include <iostream>
using namespace std;
int main()
{
    double prices[4] = {53.33, 34.55, 99.7, 23.4};

    cout << "Number of elements in array is: " << sizeof(prices) / sizeof(prices[1]) << endl;
    // OR    
    cout << "Number of elements in array is: " << sizeof(prices) / sizeof(double) << endl;    
   
    return 0;
}

    2. Display every element in an array using sizeof() through a for loop:
            You can display every element of an array by using for loop but the problem is that you have to change your code every time some new element is added to the array. So, in order to overcome this problem we can use sizeof(grades)/sizeof(char) in place of the final value. This sizeof(grades)/sizeof(char) will give us the total number of elements in the array and we will not have to change the code every time a new element is added.

#include <iostream>
using namespace std;
int main()
{
    char grades[] = {'A', 'B', 'C', 'D', 'E', 'F'};

    for (int i = 0; i < sizeof(grades)/sizeof(char); i++)
    {
        cout << grades[i] << ' ';
    }
   
    return 0;
}


6: Foreach loop:
        If you just want to display the elements in an array, foreach loop is more useful than for loop because of less syntax involved. But is very less flexible than a for loop. That's why, for complex programs, still for loop is used.

In foreach loop, in () of for loop, (i) you first have to declare one name for every element of the array and write a suitable datatype, (ii) and then add : and then (iii) write the name of the array.

In the loop, you will use the name declared for every element.

#include <iostream>
using namespace std;
int main()
{
    char grades[] = {'A', 'B', 'C', 'D', 'E', 'F'};

    for (char grade : grades)
    {
        cout << grade << ' ';
    }
   
    return 0;
}

It will be read as: For every grade in grades, let's print each grade (and print one space).


7: Pass array to a function: 

        When you pass an array to a function, it decays into what is known as a pointer. Now, this pointer has no idea what the size of array is. So, when you are trying to output array element by using sizeof() operator in for loop, it will not run.

#include <iostream>
using namespace std;
int sum_array(int x[]);

int main()
{
    int prices[] = {75, 34, 87, 56, 69};
    cout << "Total price is: Rs." << sum_array(prices) ;

    return 0;
}

int sum_array(int x[])
{
    int sum;
    for (int i = 0; i <= sizeof(x)/sizeof(int); i++)
    {
        sum += x[i];
    }
    return sum;
}

    Here as prices decay into pointer,  thats why function would never know what is the size of prices[] . So, in order to overcome this problem, we will have to check the size before and then pass it to function.

#include <iostream>
using namespace std;
int sum_array(int x[], int y);

int main()
{
    int prices[] = {75, 34, 87, 56, 69};
    int size = sizeof(prices)/sizeof(int);
    cout << "Total price is: Rs." << sum_array(prices, size) << endl;

    return 0;
}

int sum_array(int x[], int y)
{
    int sum;
    for (int i = 0; i <= y; i++)
    {
        sum += x[i];
    }
    return sum;
}

Notice: 
    1. You don't have to pass [] while passing array to function like sum_array(prices[], size) and
        sum_array(prices, size) will work the same.
    2. Remember, always pass [] during function declaration and writing function id ie:
            (a) int sum_array(int x); is wrong
            (b) int sum_array(int x[]); is correct


8: Fill elements in an array:

        You can add elements in an array using a for loop.

If you want to quit entering the elements in the array, you can add a condition like when some specific key is entered, break; condition will stop the loop and ultimately, stop entering the elements in the array. 

But there is a problem that this quitting key will also be stored as an array element. So in order to avoid this, you can save every element in temp variable and if it is not quitting variable, assign it to a specific index of that array.

#include <iostream>
using namespace std;
void print_array(string array[], int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << array[i] << '\n';
    }
}

int main()
{
    int size;
    cout << "Enter the number of elements in array: ";
    cin >> size;
    string array[size];
    string temp;
    for (int i = 0; i < size; i++)
    {
        cout << "\nPress q to Quit\nOR\nEnter the number of element at position # " << i + 1 << ": ";
        getline(cin >> ws, temp);
        if (temp == "q")
        {
            break;
        }
        else
        {
            array[i] = temp;
        }
    }

    print_array(array, size);
    return 0;
}

There is another problem, that when you are displaying array, if you have quit earlier, it would display empty spaces on the index where you havn't entered a value. So, in order to overcome this problem, you can pass an argument !array[j].empty(); which will terminate the array printing loop exactly when it finds an empty space.

#include <iostream>
using namespace std;

int main()
{
    int size;
    cout << "Enter the number of elements in array: ";
    cin >> size;
    string array[size];
    string temp;
    for (int i = 0; i < size; i++)
    {
        cout << "\nPress q to Quit\nOR\nEnter the number of element at position # " << i + 1 << ": ";
        getline(cin >> ws, temp);
        if (temp == "q")
        {
            break;
        }
        else
        {
            array[i] = temp;
        }
    }

    for (int j = 0; !array[j].empty(); j++)
    {
        cout << array[j] << endl;
    }
    return 0;
}


9: Search in an array: 
            You can search the index of a certain element in an array by the following program: 

#include <iostream>
using namespace std;
int search_array(string x[], int y, string z);

int main()
{
    string cars[] = {"corvette", "mustang", "bugatti", "mitsubishi", "ferarri", "honda", "picanto"};
    string input;

    int size = sizeof(cars) / sizeof(string);
    cout << "Enter the name of car you wanna search: ";
    cin >> input;

    int index = search_array(cars, size, input);

    if (index != -1)
    {
        cout << input << " is at index: " << index << " ie at position: " << index + 1 << endl;
    }
    else
    {
        cout << input << " is not present in the array\n";
    }

        return 0;
}

int search_array(string x[], int y, string z)
{
    int a = 0;
    for (int i = 1; i < y; i++)
    {
        if (z == x[i])
        {
            a = i;
        }
    }
    if (a != 0)
    {
        return a;
    }
    else
    {
        return -1;
    }
}

Important points in the program:

  1.   In C++, return -1; is used when something is not found in a program.
  2.  The index always starts at 0.
  3. You can find the position of an array element by doing index + 1 


10: Sort an array:


11: Fill( ) function:

        This function is used to fill an array with a range of elements with the specified value.

#include <iostream>
using namespace std;
int main()
{
    string array[100];
    // fill(begin, end, value);
    fill(array, array + 100, "Pizza");

    for (string elements : array)
    {
        cout << elements << ' ';
    }
    return 0;
}

Within fill(array, array + 100, "Pizza") :

  • array argument specify the starting point of an array.
  • array + 100 specify the ending point ie filling of the array will stop at 100 index.
  • "Pizza" is the element with with array is being filled with.

Now you can also take the size of array from user.

#include <iostream>
using namespace std;
int main()
{
    int size;
    cout << "Enter the size of the array: ";
    cin >> size;

    string array[size];
    // fill(begin, end, value);
    fill(array, array + size, "Pizza");

    for (string elements : array)
    {
        cout << elements << ' ';
    }
    return 0;
}

You can also make it constant but then you cannot take input in it.

#include <iostream>
using namespace std;
int main()
{
    const int size = 100;
   
    string array[size];
    // fill(begin, end, value);
    fill(array, array + size, "Pizza");

    for (string elements : array)
    {
        cout << elements << ' ';
    }
    return 0;
}

If you have to fill half of the array and second half remains empty:
Just divide total size with 2.

#include <iostream>
using namespace std;
int main()
{
    int size;
    cout << "Enter the size of the array: ";
    cin >> size;

    string array[size];
    fill(array, array + size / 2, "Pizza");

    for (string elements : array)
    {
        cout << elements << '\n';
    }
    return 0;
}

If you want to fill half of the array with one type of element and other half with other type,
End the first fill function at half, and now start the second fill function at half and end at the end.

#include <iostream>
using namespace std;
int main()
{
    int size;
    cout << "Enter the size of the array: ";
    cin >> size;

    string array[size];
    fill(array, array + size / 2, "Pizza");
    fill(array + size / 2, array + size, "Burger");

    for (string elements : array)
    {
        cout << elements << '\n';
    }
    return 0;
}

If you want to fill 1/3rd of array with one element, 2/3rd with second element and 3/3rd with third element,
Here first ending has a fraction 1/3, second ending has a fraction of 2/3, and the third ending has a fraction of 3/3 ie 1.

#include <iostream>
using namespace std;
int main()
{
    int size;
    cout << "Enter the size of the array: ";
    cin >> size;

    string array[size];
    fill(array, array + size / 3, "Pizza");
    fill(array + size / 3, array + size / 3 * 2, "Burger");
    fill(array + size / 3 * 2, array + size, "Shawarma");

    for (string elements : array)
    {
        cout << elements << '\n';
    }
    return 0;
}


12:     














Comments

Popular posts from this blog

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_