Question

In: Computer Science

Explain how arrays allow you to easily work with multiple values? Explain the relationship between the...

Explain how arrays allow you to easily work with multiple values?

Explain the relationship between the length and valid indexes of an array?

Why do we need to pass a size as well as the array to any function/procedure where we want it to use this array?

Explain how for loops can be used to work effectively with elements in an array?

How could you print out the names in the array starting with the last name and working back to the first name?

Provide an example of using a for loop without an array?

C++ programming related questions

Solutions

Expert Solution

Q:- Explain how arrays allow you to easily work with multiple values?

Ans:- In C++ programming, Arrays are very useful while dealing with multiple values.

Let us take a real life example. Suppose you need to take 100 numbers as an input from the user and calculate the sum & average of those numbers. So what will you do? Are you thinking to take 100 variables in your program to store those 100 numbers? No, right?

Consider the C++ program snipet:-

int main(){

               int a1, a2, a3,………;

               cout<<”Please enter the 100 numbers”;

               cin>>a1>>a2>>a3>>a4>>……..;    //

}

If you are thinking to do programming in this way, you need to think for the better approach. And for that you need to know about the concept of arrays, which are there to help you in these kind of problems.

Consider the C++ program snipet with Array :-

int main(){

int arr[100] ;

               cout<<”Please enter the 100 numbers”;

               for(int i=0;i<100;i++)

                              cin>>arr[i];

}

So, here you can clearly see that with the use of an array, you need not to think about the names of 100 or any other possible numbers of variables, which is point of concern when you want to do better programming and you have to take care of the naming conventions. Simply, we can remember a single name of array and we can work with multiple values.

Q:- Explain the relationship between the length and valid indexes of an array?

Ans:- To understand the relationship between the length and the valid indexes of an array, we need to understand the memory management of the C++ program and mainly in case of arrays.

There are mainly two types of memory places, for which a programmer need to care about. One is stack and other is heap. From stack, memory is allocated when we declare the size of an array in the code itself and do not change. But in case of heap, we can allocate memory dynamically while executing the program. For now, our main concern is stack memory.

Let us see how an array looks like in memory:-

1

2

3

4

5

Arr[0]                                  arr[1]                                   arr[2]                    arr[3]                                   arr[4]

X1000                                  x1004                                  x1008                   x1012                                  x1016

                                                            Fig: Memory representation of an array

Here we took an array to store 5 numbers. We can access these elements by name of an array along with its index eg: arr[1]. The main point to notice here is when we declare an array of a given size, C++ program remembers only the base address of the array. Here we represented it as x1000. From there it calculates the address of other elements by using the formula :-

                              Base address + (index * size of data type)

Eg: address of arr[3] = x1000 + 3*4      // 4 bytes for Integer

Also,

               Total memory allocated to an Array = Number of elements * size of one element

So now we are ready to maintain the relation between length and valid indexes of an array. Now as we discussed array is contiguous memory location which is allocated while declaring the array. If we will try to access the 5th and 10th index of this array, then try to think what will happen. Applying the formula, which C++ compiler will use:

               Arr[5] = x1000 + 5*4 = x1020

               Arr[10] = x1000 + 10*4 = x1040

Here x1020 and x1040 is an unknown memory for the C++ compiler. Compiler doesn’t know what is there in these memory locations. It just knows that at x1000 an array is there with size of 5 integer type elements. If you will try to access the other elements, compiler will show you some garbage values.

Consider the code snipet:-

int main(){

int arr[] = {1,2,3,4,5};

cout<<arr[10];

}

This program will give you the output as some garbage value. The reason behind this is compiler of C++ doesn’t do any bound checking, it will go to the memory location and print the value that is available there. Here we call this value as garbage values. But if you will assign some value to this memory location, then it will show you this value.

Consider the code snipet:-

int main(){

int arr[] = {1,2,3,4,5};

arr[10] = 10;

cout<<arr[10];

}

This program will give you the output as 10.

So now we can conclude that valid indexes of an array are those values which are within the range of the size of the array. If you will try to access the index beyond the size of the array, program might misbehave and give you the garbage values.

Q:- Why do we need to pass a size as well as the array to any function/procedure where we want it to use this array?

Ans:- As we know, functions are code snipets which we use to make use of some functionality many number of times. Again we need to understand the memory allocation of a function. Whenever we call a function, it takes place in stack memory.

Consider the code snipet:-

int main(){

int arr[] = {1,2,3,4,5};

               add(arr,5);

}

void add(int arr[], int size){

int sum=0;          

for(int i=0;i<size;i++)

                              sum = sum + arr[i];

               cout<<sum;

}

Consider this figure:-

Whenever we call a function, it takes place in stack in this way. Assume we are giving any values to the function add().

Add()

main() ; arr[5] = {1,2,3,4,5}

Now, as we can see if we don’t provide the function information about the array then it won't be able to understand what is the base address of the array and what is the size of this array. So to solve this problem we always give the function information about the size of the array and base address. So that it should know what is the memory which is pointing to the array and up to where it need to go to perform its task. After giving these values it will look like this.

Add(); size =5; arr[0] = x1000;

main() ; arr[5] = {1,2,3,4,5}

Q:- Explain how for loops can be used to work effectively with elements in an array?

Ans:- With the elements of the array, we always feel that it is very efficient to use the for loop instead of while or do-while loop. To proof this point, we need to understand the working behavior of these loops, so that we can differentiate how for loop is efficient.

Let us consider the syntax of for loop: -

Int main(){

               Int Arr[] = {1,2,3,4,5};

Int sum =0;

For(int I =0 ; I<5; i++)

               Sum = sum +arr[i];

}             

Dry run:

  1. I=0 , 0<5 is true
  2. Sum = 0 +1 =1
  3. I incremented to 1
  4. I=1, 1<5 is true
  5. Sum = 1+2 = 3
  6. I is incremented to 2
  7. I=2 , 2<5 is true
  8. Sum = 3 +3 =6
  9. I incremented to 3
  10. I=3 , 3<5 is true
  11. Sum = 6+4 =10
  12. I incremented to 4
  13. I=4 , 4<5 is true
  14. Sum = 10 +5 =15
  15. I incremented to 5
  16. I=5, 5<5 false
  17. Loop ends

Let us now take the example of this code with while loop:-

Int main(){

               Int Arr[] = {1,2,3,4,5};

Int sum =0;

Int i=0;

While(i<5) {

               Sum = sum +arr[i];

               I++;

}             

}             

However, the dry run of the while loop is exactly similar to the for loop. But one thing is more noticing is that for loop is very compact and we are saving line of codes in for loop. And moreover it is very easy to understand and apply for loop with the arrays because of its very important features that it allows initialization, incrementation/decrementation and condition checking in single line of code that allows the programmer clear insight of code that how to deal with array. Eg:- Go to the first index of array, check whether index is within the size of array, perform the action and go to the next index.

Q:- How could you print out the names in the array starting with the last name and working back to the first name?

Ans:- Consider the code snipet:-

#include<iostream>

using namespace std;

int main(){

string arr[5] = {"abc","def","ghi","jkl","mno"};

for(int i=4; i>=0; i--){

    cout<<arr[i]<<" ";

}

}

Here I have used the array of string type to store some names. Then I used a for loop starting from the last index of the array and going back to the first index of the array and printing the values of the array in the backward manner.

Q:- Provide an example of using a for loop without an array?

Ans:- There are lots of examples you can think of where you can apply loops without the use of an array.

Consider you want to just print the numbers from 1 to 10. Or you want to print the table of 2.

Consider the code snipet :-

To print numbers from 1 to 10:-

#include<iostream>

using namespace std;

int main(){

    for(int i=1;i<=10;i++)

        cout<<i<<" ";

}

To print the table of 2:-

#include<iostream>

using namespace std;

int main(){

    for(int i=1;i<=10;i++)

        cout<<"2"<<"*"<<i<<"="<<2*i<<endl;

}


Related Solutions

Explain the difference between Arrays and ArrayList. What are the limitation of arrays? How many primitive...
Explain the difference between Arrays and ArrayList. What are the limitation of arrays? How many primitive data types Java have? Please list them out and list the corresponding wrapper classes for each type. What is the different between String class and StringBuilder class?
Investigate the relationship between crying and IQ Infants who cry easily may be more easily stimulated...
Investigate the relationship between crying and IQ Infants who cry easily may be more easily stimulated than others. This may be a sign of higher IQ. Child development researchers explored the relationship between the crying of infants four to ten days old and their later IQ test scores. The researchers recorded the crying of babies and measured its intensity by the number of peaks in the most active 20 seconds. They later measured the children’s IQ at age three years...
1) a) Give short code example of parallel arrays. b) Explain how parallel arrays work. 2)...
1) a) Give short code example of parallel arrays. b) Explain how parallel arrays work. 2) a) How would you compare two arrays to check if they have the same values? b) Assume array1 and array2 are int arrays with 10 elements in each. if(array1 == array2) What is this comparing? 3 a) Can you encounter memory violation using an array? b) If yes explain. If no, explain why not.
How would you assess the relationship between social value and perception? Is there a relationship? Explain.
How would you assess the relationship between social value and perception? Is there a relationship? Explain.
Explain the relationship between spirituality, religion and social work practice
Explain the relationship between spirituality, religion and social work practice
1. With respect to resizable arrays, establish the relationship between the size of the array and...
1. With respect to resizable arrays, establish the relationship between the size of the array and the time it takes to perform random access (read a the value stored at a given position somewhere in the array). Provide empirical evidence to support your answer.
With reference to the relationship between stock prices and options values, explain what boards of directors...
With reference to the relationship between stock prices and options values, explain what boards of directors are trying to achieve when they award CEOs options as part of their executive compensation packages.
what is the relationship between linear, multiple and logistic regrerssion
what is the relationship between linear, multiple and logistic regrerssion
There is close relationship between risk managment and the construction contract. Explain that relationship and how...
There is close relationship between risk managment and the construction contract. Explain that relationship and how it is established. If you don’t use Word Microsoft to write the solutions there, so write very big. Thank you
You work for an insurance company and are studying the relationship between types of crashes and...
You work for an insurance company and are studying the relationship between types of crashes and the vehicle involved. As a part of your study, you randomly selected 3571 vehicle crashes and organize the resulting data as shown in contingency table. At 0.10 can you conclude that the type of crash depends on the type of vehicle? Type of crash. Car. Pickup. Spot utility Single vehicle 840. 307. 327 Multiple vehicle 1177 486. 434 Caculate the degrees of freedom d.f....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT