Reverse the output of the array, look for an element

 Source:

#include <iostream>

#include <algorithm>

#include <functional>

#include <iomanip>

#include <stdlib.h>

const int MAXSIZE = 10;

using namespace std;

 

InitArray int * ()

{

  int i;

  int * p = new int [10]; // allocate a dynamic array of 10 integers, the first address pointer p to an array

  for (i = 0; i<10; i++)

    p [i] = -1; // for each cell in the array are assigned -1

  return p; // returns an array of first address

}

// reverse printing of realization

void reverse(int b[])

{

  for (int i = 0; i<MAXSIZE/2; i++)

  {

    int temp;

    temp = b[i];

    b[i] = b[MAXSIZE-1 - i];

    b[MAXSIZE-1 - i] = temp;

  }

}

// Find the value of K elements in the array

int search (int A [], int n, int k) // because the array has a reverse order, so in the calculation of several elements

{// when, starting from the rearmost

  int i = 0; // At this time, the number should start from the front

  while (i < n)

  {

    if (A[i] != k)

      i++;

    else

    break;

  }

  return i;

}

int main ()

{

  int a[10]={34,5,8,12,15,35,69,40,33,19};

  int * b = InitArray ();

  int i;

  for (i = 0; i < 10; i++)

    b[i] = a[i];

  cout << "number in the array is:" << endl;

  for (i = 0; i < 10; i++)

    cout << setw(4) << a[i];

  cout << endl;

 

  cout << "reverse output array:" << endl;

  reverse (b); // reverse printing

 

  for (i = 0; i < MAXSIZE; i++)

    cout << setw (4) << b [i]; // value of the output array

  cout << endl;

  /*

  int * p = b; // pointer output 

  for (; p < b + 10; p++)

  cout << setw(5) << *p;

  */

 

  int x;

  cout << "\ n Find a number in the array, if found to display its position, did not find the show -1" << endl;

  cout << "Please enter the number you are looking for:";

  scanf("%d", &x);

  int pos = search(a, 10, x);

  if (pos < 10)

    cout << "position this number is:" << pos + 1 << endl;

  else

  cout << "- 1 without this number \ n!" << endl;

  system("pause");

  return 0;

}

 

 

 

 operation result:

 

Guess you like

Origin www.cnblogs.com/duanqibo/p/11118452.html