Code:
#include <stdio.h>
#define ARR_SIZE 20
int in_array(int[], int, int);
int is_int(int);
int main()
{
int i = 0, num, numbers[ARR_SIZE];
// populating the array
for(i = 0; i < ARR_SIZE; i++)
{
if(i > 0)
{
printf("%i number(s) entered so far.", i);
}else{
printf("No numbers entered so far.");
}
printf("\nEnter an integer: ");
scanf("%i", &num);
fflush(stdin);
printf("\n");
/**
* If the number entered is already in the array, inform the idiot and ask them to enter a different number
* Also ensure that the idiot entered a number so your program doesn't crash
*/
while(in_array(numbers, num, i) == 1 || is_int(num) == 0)
{
if(is_int(num) == 0)
{
printf("Please refer to http://en.wikipedia.org/wiki/Integer.\n");
printf("If you have read the article and understand what an integer is;\nPlease enter one now: ");
}else{
printf("%i is already in the array, enter another number: ");
}
scanf("%i", &num);
fflush(stdin);
printf("\n");
}
numbers[i] = num;
}
/*printing a comma separated list of all integers in the array*/
for(i = 0; i < ARR_SIZE; i++)
{
printf("%i", numbers[i]);
if(i != (ARR_SIZE-1))
{
printf(", ");
}
}
return 0;
}
/**
* Checks if an integer is in an array of integers.
* @param int numbers[] the array of integers.
* @param int num the number that is being checked for in the array.
* @param int limit the highest index in the array to check.
*/
int in_array(int numbers[], int num, int limit)
{
int found = 0;
int i;
for(i = 0; i <= limit; i++)
{
if(numbers[i] == num)
{
found = 1;
}
}
return found;
}
int is_int(int num)
{
/*This is just a dummy check. You will need a more thorough check as this won't work as expected.*/
if(sizeof(num) == sizeof(int))
{
return 1;
}else{
return 0;
}
}