How this C++ program works and how to trace it?

Guys I really want to know how this program works. Please explain this program to me because I don't understand its variables and their respective task. Please help me trace its different loops so that we will know the flow of the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
using namespace std;

int main()
{
  int z,y=0,s=0,c,b,t;
  int a[20]={23,45,1,23,5,78,6,13,1,4,78,18,3,5,26,4,5,10,3,45};
  
  cout<<"Input number to be searched: ";
  cin>>z;

  int j=0;

  for(b=0; b<=19;b++)
   {
     if(z==a[b])
       {
        y=y+1;
        j=1;
       }
   }
   if(j==1)
      {
        cout<<"Number of occurence of the searched item: "<<y<<endl;
        cout<<"Respectively array locations of the searched item in the array: ";
      }
  for(c=0;c<=19;c++)
    {
      if(z==a[c])
        {
           cout<<c<<" ";
        }
    }
  
  if(j==0)
   {
    for(b=0;b<=19;b++)
     {
      for(c=0;c<=18;c++)
        {
         if(a[c]>a[c+1])
          {
           t=a[c];
           a[c]=a[c+1];
           a[c+1]=t;
          }
        }
     }
    cout<<"\nThe Largest element in the array is: "<<a[19]<<endl;
    cout<<"The smallest element in the array is: "<<a[0]<<endl;
   }
 return 0;
}
this whole code has two parts to it. it only executes one of them.

the first part is if j == 1
the second part is if j == 0

at the beginning, this code takes an integer input from the user then begins to search for it in the array called 'a'
after finding it, it tells you how many times it was found in the array then tells its position in the array for each occurrence.

if the integer input is NOT found in the array, the second part executes.
what it does is rearrange the array from smallest to largest by having a nasty nested loop to do it. it checks if the number next to it in the array is greater than it then it switches places if so.

then it prints the last element which is the largest and then the first element which is the smallest.

also the integer 's' is never used
this whole code has two parts to it. it only executes one of them.

This statement is false.
Topic archived. No new replies allowed.