SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Arrays
Exercise:
Self-test Exercises
Question:7 | ISBN:9780321531346 | Edition: 7

Question

What is wrong with the following piece of code?

int sample_array[10];

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

sample_array[index] = 3*index;

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Error statement in the given code:

int sample_array[10];

Explanation:

  • The range of sample_array is 10. It represents sample_array[0] through sample_array[9].
  • The "for" loop denotes the begins index=1 to index <=10. So, index 10 in ample_array[10] is out of range. 
  • So, need to change the initialize the index size of sample_array. That is, sample_array[11];

Correct code:

int sample_array[11];
for (int index = 1; index <= 10; index++)
sample_array[index] = 3*index;

 

0 0

Discussions

Post the discussion to improve the above solution.