Home > Back-end >  C How to store odd numbers in an array and access them using a pointer notation?
C How to store odd numbers in an array and access them using a pointer notation?

Time:09-22

I found an error in the book solution, the below solution is using the pointer notation to access the array as requested, but the printed results are not odd numbers, instead its printing 1 to 50 and 50 - 1.

Original instructions: Write a program that declares and initializes an array with the first 50 odd (as in not even) numbers. output the numbers from the array ten to a line using pointer notation and then output them in reverse order, also using pointer notation.

Below attaching the wrong solution from the book, appreciate your help:

// Storing odd numbers in an array and accessing them using pointer notation


#include <iostream>
#include <iomanip>

int main()
{
  const size_t n {50};
  size_t odds[n];
  for (size_t i {}; i < n;   i)
    odds[i] = i   1;

  const size_t perline {10};
  std::cout << "The numbers are:\n";
  for (size_t i {}; i < n;   i)
  {
    std::cout << std::setw(5) << *(odds   i);
    if ((i   1) % perline == 0)                        
      std::cout << std::endl;
  }

  std::cout << "\nIn reverse order the numbers are:\n";
  for (int i {n - 1}; i >= 0; --i)                    
  {                                                    
    std::cout << std::setw(5) << *(odds   i);
    if (i % perline == 0)
      std::cout << std::endl;
  }
}

CodePudding user response:

Just write

for (size_t i = 0; i < n;   i)
{
    odds[i] = 2 * i   1;
}

And the last loop rewrite using the variable i of the type size_t like

for ( size_t i = n; i != 0; --i )                    
{                                                    
    std::cout << std::setw(5) << *(odds   i - 1 );
    if (i % perline == 0)
        std::cout << std::endl;
}

or like

for ( size_t i = n; i-- != 0; )                    
{                                                    
    std::cout << std::setw(5) << *(odds   i );
    if (i % perline == 0)
        std::cout << std::endl;
}
  • Related