How to perform the needed search process for array elements?

Please Help me revise or improve the program because it has a logical error.

Write a program that will search for the number of an item in the array num[20]={23,45,1,23,5,78,6,13,1,4,78,18,3,5,26,4,5,10,3,45}. If the search item is in the array, count the number of occurrence of that number in the array and determine their respective array locations. If the search item is not in the array, the algorithm has to determine the largest and the smallest element in the given array.

Here's my code that needs to be revise please help me...

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
54
#include<iostream>
using namespace std;

int main()
{
	int num[20]={23,45,1,23,5,78,6,13,1,4,78,18,3,5,26,4,5,10,3,45};
	int search,c,n,big,small;
	float m,oc;
	
	//search the item in the array
	cout<<"Enter the number to search\n";
	cin>>search;
	 	
	while(search>0)
	 {
	 	m=search%10;
	 	if(m==c)
	    oc++;
	    search=search/10;
	 }//show the occurrence
	cout<<"Digit occurred "<<oc<<" times";
	
	//show respective array locations
	for(c=0; c<20; c++)
	 {
	 	if(num[c]==search)
	 	 {
	 	 	cout<<search<<" is present at location"<<c+1;
	 	 	break;
	 	 }
	 }
	//show the largest and the smallest element  
	if(c==num[20])
	 {
	    big=num[0];
	    for(c=1; c<num[20]; c++)
	     {
	 	 if(big<num[c])
	 	  {
	 	    big=num[c];
	 	  }
	     }
	    cout<<"Largest element : "<<big;
	 
	    small=num[0];
	    for(c=1; c<num[20]; c++)
	     {
	  	   if(small>num[c])
	  	   small=num[c];
	     }
	     cout<<"Smallest element : "<<small;
        }
   return 0;
}

This should be the Output

Enter the number to search : 23
Digit occurred : 1
23 is present at location 1;
 
if the searched Item is not in the array
 
Largest element : 78
Smallest element : 3

But the output of my program is wrong please do help me guys.
Last edited on
Some parts of your program is correct but your algorithm, variable usage does not look right.

Some things to start of with:
1) No need of using float variables. Change them to int.
2) Line 14 to 21 is not needed. That is not the way to count your occurrences
3) Remember, you have to print all the occurrences of the number match, so remove the break statement in line 29
4) I would have a flag, initialized to false and set it to true when there is a match. This should probably go into line29, instead of break.
5) Change if condition on line 33, check to see if match flag is false.

Hope this helps
You should also initialize variables before you use them, otherwise they will just be filled with junk values.
Please give me some codes because I am having difficulties in debugging my program I hope this helps also
Topic archived. No new replies allowed.