c++ char array

Need help with my code. please!

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;
void displayTheUnion (char a[], char b[], char u, char i){ //this will display the union of the given letters.
int k=0, l=0;
while (k<u && l<i){
if(a[k]<b[l]) //if the first letter of set A is different from set B then display the first letter of set A
cout<<a[k++];
else if(b[l]<a[k]) //same method, display the first letter of set B and so on.
cout<<b[l++];
else{
cout<<b[l++]; 
k++;
}
}
while(k<u)
cout<<a[k++]; //display the other letters
while(l<i)
cout<<b[l++];
}
void displayTheIntersection (char a[], char b[], int u, int i){ //this will display the intersection of the given letters.
int k=0, l=0;
while(k<u && l<i){
if(a[k]<b[l]) // as mentioned earlier it is the same with the union part.
k++;
else if(b[l]<a[k])
l++;
else if (a[k]==b[l]){ //if the two letters are the same the program will display it.
cout<<b[l++];
k++;
}
}
}

void main()
{
char a[5], b[5];
int u= sizeof a/sizeof a[0];
int i= sizeof b/sizeof b[0];
cout<<"Enter letters for set A: ";
for(int x=0; x<5;x++){
cin>>a[x];
}

cout<<"Enter letters for set B: ";
for(int y=0;y<5; y++){
cin>>b[y];
}
cout<<"The union is: ";
displayTheUnion (a,b,u,i);
cout<<endl;
cout<<"The intersection is: ";
displayTheIntersection (a,b,u,i);
cout<<endl;
}
Well to start off, tell us your problem specifically so that we can help you. Secondly, your code is extremely difficult to read. Add spaces between commas and spaces before and after { and }

:)
You will find your code much easier to read and handle if you indent it properly.

Line 34: main() must return int.

displayIntersection and displayUnion assumes that the arrays are sorted, but I don't see any code that sorts them. If you enter the arrays in sorted order, then the code works fine:
1
2
3
4
5
$ ./foo
Enter letters for set A: abcef
Enter letters for set B: acefh
The union is: abcefh
The intersection is: acef


Topic archived. No new replies allowed.