array can't check for user input duplicate integers
I have written the program below. I would like the user to input 4 unique integers. Whenever the user inputs a duplicate I want them to be prompted with an "error" message, and then the program should repeat until the user finishes inputting 4 unique integers(no repeats).
Code:
#include<stdio.h> Code:
Enter> 1 Code:
Enter> 3 |
Why are you always reading into &arr[MAX]? Not only is the input not going into the "element"th index in arr where it can later be checked, arr[MAX] is undefined memory as well.
There's also a problem with your for loop This: Code:
for(dup=element-1;dup-- >0;) |
Quote:
Code:
/* C program to find the sum marks of n students using arrays */ |
Bear in mind, especially when using "C," that "there's one way to do it." In this instance, you should consider that there is one right-way to write a For-loop:
for ... ( initial_condition ; test ; increment_or_decrement ) { ... Don't put "side effect" into the first two clauses. Write exactly what the next programmer who will follow you, expects to see. I also strongly advise that you start your work with ... a number-two pencil and a legal pad. :eek: I am perfectly serious. I'm taking a short break right now and then it will be back to the pencil-and-pad to continue sketching out an algorithm. All of the pages on that pad are kept. Eventually, the pad itself will go into a banker's box in which I (still) keep them. I have years' worth of now-interesting legal pads in that box. Work out your thoughts, clearly, on paper ... first. If you change your mind, lightly "X"-through the page, flip over to the next one, and try again ... keeping them all. When you finally achieve clarity as to what it is you're setting out to do, "doing it" is the very-easy part. Whereas, if you try to "ride the pony bareback," yes, you probably will arrive someplace, but you will have at the same time discovered where all of the thorn-bushes are located along the very-circuitous route. |
Quote:
|
Ouch!!
Quote:
I have already changed it to Code:
scanf("d",&arr[element]); Unfortunately, the program still makes the same output, but at least now it is one step closer to the final goal. |
Quote:
Code:
scanf("%d",&arr[element]); |
I manually typed that part
Quote:
|
soln :)
I made the following changes:
Code Changed: 1) for(dup=element-1;dup>0;dup--)----------> for(dup=element-1;dup>=0;dup--) // **** {">" to ">="} ***** 2) Moved "error=0;" from below "//Initialize values" to just below do. 3) Changed if(arr[element]==arr[dup]) section's "error=1;" to "error+=1;" and got rid of "error=0;" in following else if section. Final results (Success at last!) Code:
Enter> 1 FINAL PROGRAM (Freedom at last!) Code:
#include<stdio.h> |
All times are GMT -5. The time now is 09:30 AM. |