So I need to do C program that asks 20 integers from user (number between 10-100) and print only the numbers that occurs only once.
#include <stdio.h>
int main() {
int n;
int i=20;
while(i-- && n <100 && n>10)
{
scanf("%d", &n);
}
printf("Number is not between 10-100. Try again");
return 0;
}
You need to remember the numbers in the array and check for repetitions.
Here you have a naive implementation (you can improve many things). Instead of user input I fill the array with random (pseudo random) numbers
void printDistinct(int *arr, size_t size)
{
for(size_t cnum = 0; cnum < size; cnum++)
{
int isDistinct = 1;
for(size_t index = 0; index < size; index++)
{
if(index != cnum)
if(arr[cnum] == arr[index])
{
isDistinct = 0;
break;
}
}
if(isDistinct)
printf("arr[%zu] = %d\n", cnum, arr[cnum]);
}
}
#define NNUM 50
int main(void)
{
int arr[NNUM];
srand(time(NULL));
for(size_t i = 0; i < NNUM; i++)
{
arr[i] = rand() % 50;
}
printDistinct(arr, NNUM);
}
https://godbolt.org/z/7a9ejfrav
Related
#include <stdio.h>
#include <math.h>
#define MAX_SIZE 10000
int main(void)
{
int a[MAX_SIZE];
int N;
int L; /* the current size of the list */
/* read in the upper limit. Keep reading until
a valid number between 3 and the maximum that
can be handled by the array is entered */
double b[10000];
int j, i;
L = 0;
printf("Enter the upper limit:\n");
do {
scanf("%d", &N);
} while (N<3 || N>MAX_SIZE+2);
int prime;
for (j = 1; j < N; j++)
{
prime = 1;
for (i = 2; i < j; i++)
{
if (j % i == 0)
{
prime = 0;
break;
}
}
if (prime)
{
a[i] = j;
L++;
}
}
/* write out the result - DO NOT CHANGE THIS */
for(i=0;i<L;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
Program needs to take an integer, calculate primes below that integer, print that list of primes.
I think my problem is related to the loops.
The program is calculating the primes but listing 0 if the number previously there isnt prime eg a[4] is now printing as 0
Any help is appreciated.
thanks.
Is this what you were trying to implement?
#include <stdio.h>
#define MAX_SIZE 100
int main(void)
{
int primes[MAX_SIZE];
int primes_found = 0;
int limit = 0;
while (limit < 3)
{
printf("Enter the upper limit:\n");
scanf("%d", &limit);
}
for (int candidate = 2; candidate <= limit && primes_found < MAX_SIZE; candidate++)
{
int divisor = 2;
int is_prime = 1;
while(is_prime && divisor < candidate)
is_prime = candidate % divisor++ != 0;
if (is_prime)
primes[primes_found++] = candidate;
}
for (int i = 0 ; i < primes_found ; i++)
printf("%d ", primes[i]);
printf("\n");
return 0;
}
I am having trouble achieving the wanted results. The program should ask for 20 inputs and then go over each to see if they appear more than once. Then only print out those that appeared once.
However currently my program prints out random numbers that are not inputted.
For example:
array = {10,10,11,12,10,10,10.....,10} should return 11 and 12
#include <stdio.h>
void main() {
int count, size=20, array[size], newArr[size];
int number=0;
for(count = 0; count < size; count++) {
// Ask user for input until 20 correct inputs.
printf("\nAnna %d. luku > ", count+1);
scanf("%d", &number);
if( (number > 100) || (number < 10) ) {
while(1) {
number = 0;
printf("Ei kelpaa.\n");//"Is not valid"
printf("Yrita uudelleen > ");//"Try again >"
scanf("%d", &number);
if ( (number <= 100) && (number >= 10) ) {
break;
}
}
}
array[count] = number;
}
for(int i=0; i < size; i++) {
for(int j=0; j<size; j++){
if(array[i] == array[j]){
size--;
break;
} else {
// if not duplicate add to the new array
newArr[i] == array[j];
}
}
}
// print out all the elements of the new array
for(int k=0; k<size; k++) {
printf("%d\n", newArr[k]);
}
}
You don't need the newArr here, or the separate output loop. Only keep a count that you reset to zero at the beginning of the outer loop, and increase in the inner loop if you find a duplicate.
Once the inner loop is finished, and the counter is 1 then you don't have any duplicates and you print the value.
In code perhaps something like:
for (unsigned i = 0; i < size; ++i)
{
unsigned counter = 0;
for (unsigned j = 0; j < size; ++j)
{
if (array[i] == array[j])
{
++counter;
}
}
if (counter == 1)
{
printf("%d\n", array[i]);
}
}
Note that the above is a pretty naive and brute-force way to deal with it, and that it will not perform very well for larger array sizes.
Then one could implement a hash-table, where the value is the key, and the count is the data.
Each time you read a value you increase the data for that value.
Once done iterate over the map and print all values whose data (counter) is 1.
Use functions!!
Use proper types for indexes (size_t).
void printdistinct(const int *arr, size_t size)
{
int dist;
for(size_t s = 0; s < size; s++)
{
int val = arr[s];
dist = 1;
for(size_t n = 0; n < size; n++)
{
if(s != n)
if(val == arr[n]) {dist = 0; break;}
}
if(dist) printf("%d ", val);
}
printf("\n");
}
int main(void)
{
int test[] = {10,10,11,12,10,10,10,10};
printdistinct(test, sizeof(test)/sizeof(test[0]));
fflush(stdout);
}
https://godbolt.org/z/5bKfdn9Wv
This is how I did it and it should work for your:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
void printdistinct(const int *muis, size_t size);
int main()
{
int loop=20,i,muis[20],monesko=0;
for(i=0; i<loop; i++){
monesko++;
printf ("Anna %d. luku: \n",monesko);
scanf("%d", &muis[i]);
if (muis[i]<10 || muis[i]>100){
printf("Ei kelpaa!\n");
muis[i] = muis[i + 1];
printf("YRITÄ UUDELLEEN:\n ");
scanf("%d", &muis[i]);
}
}
printdistinct(muis, sizeof(muis)/sizeof(muis[0]));
fflush(stdout);
return 0;
}
void printdistinct(const int *muis, size_t size)
{
for(size_t s = 0; s < size; s++)
{
int a = muis[s];
int testi = 1;
for(size_t n = 0; n < size; n++){
if(s != n) {
if(a == muis[n]){
testi = 0;
break;
}
}
}
if(testi) {
printf("%d \n", a);
}
testi = 1;
}
printf("\n");
}
This approach uses some memory to keep track of which elements are duplicates. The memory cost is higher, but the processor time cost is lower. These differences will become significant at higher values of size.
char* duplicate = calloc(size, 1); // values are initialized to zero
for (unsigned i = 0; i < size; ++i)
{
if(!duplicate[i]) // skip any value that's known to be a duplicate
{
for (unsigned j = i + 1; j < size; ++j) // only look at following values
{
if (array[i] == array[j])
{
duplicate[i] = 1;
duplicate[j] = 1; // all duplicates will be marked
}
}
if (!duplicate[i])
{
printf("%d\n", array[i]);
}
}
}
What you can do is you can initialize a hashmap that will help you store the unique elements. Once you start iterating the array you check for that element in the hashmap. If it is not present in the hashmap add it to the hashmap. If it is already present keep iterating.
This way you would not have to iterate the loop twice. Your time complexity of the algorithm will be O(n).
unordered_map < int, int > map;
for (int i = 0; i < size; i++) {
// Check if present in the hashmap
if (map.find(arr[i]) == map.end()) {
// Insert the element in the hash map
map[arr[i]] = arr[i];
cout << arr[i] << " ";
}
}
Can someone help me to figure out why my code is unable to accurately find the duplicate of elements?
#include <stdio.h>
int main() {
int array[10];
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < 10; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = i + 1; j < 10; j++) {
if (array[i] == array[j]) {
count++;
break;
}
}
}
printf("The duplicates are : %d ", count);
}
I'm a beginner at this language so any advice and suggestions to help me solve this exercise will be much appreciated.
First of all the first loop runs 10 times even if the user enters less numbers. You can fix that by doing:
for (int i = 0; scanf_s("%d", &array[i]) == 1 && i < 10; i++);
Then the logic of the other two loops is wrong. I initially got wrong what you meant. I thought you wanted to know how many times a number is duplicated. So I wrote the wrong program and then modified it for your purposes. Here is your program:
#include <stdio.h>
int main() {
int n[10];
int dupes[5], d = 0;
int flag = 1, omg;
for ( omg = 0; scanf("%d", &n[omg]) == 1 && omg < 10; omg++);
for (int i = 0; i < omg; i++) {
for (int j = i+1; j < 10; j++) {
if( n[i] == n[j] ) {
if( d > 0 ) {
for(int k = 0; k < d; k++) {
if( n[i] == dupes[k] ) {
flag = 0;
break;
}
}
}
if( flag ) {
dupes[d] = n[i];
++d;
break;
}
else {
flag = 1;
break;
}
} // end outer if
}
}
printf("There are %d numbers that have at least one dupe\n", d);
return 0;
}
I named a variable omg out of desperation, writing this program was a nightmare. (Because it came from the ashes of a previous program)
Your code correctly determines the number of duplicate entries in the array.
If instead you want to determine the number of duplicated values, you must modify the algorithm:
#include <stdio.h>
int main() {
int array[10] = { 0 };
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < 10; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (array[i] == array[j]) {
if (i < j)
count++;
if (i != j)
break;
}
}
}
printf("There are %d duplicate values\n", count);
return 0;
}
I use a structure 'Number' which contains the number and its duplicate, then I fill the array and I put it in ascending order then I calculate the number of duplicate of each number and I fill in the strecture like this :
my code:
#include <stdio.h>
#define size 10
typedef struct Number
{
int number;
int duplicate;
}Number;
int main()
{
int array[size];
Number array2[size];
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
int temp=size;
int temppppp=0;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(array[i]>array[j])
{
temppppp=array[i];
array[i]=array[j];
array[j]=temppppp;
}
}
}
printf("\n\n");
for (int i = 0; i < size; i++)
{
printf("[%d]",array[i]);
}
printf("\n\n");
int i=0;
int j=0;
while(i<size)
{count=1;
while(i<(size-1)&&array[i]==array[i+1])
{
count++;
i++;
}
if(count>=2)
{
array2[j].number=array[i-1];
array2[j].duplicate=count;
j++;
}
i++;
}
int p=0;
while(p<j)
{
printf("\n[%d] has duplicated %d times !\n",array2[p].number,array2[p].duplicate);
p=p+1;
}
printf("\n\n");
printf("\nThere are %d duplicate values\n", j);
}
This program uses an array and three functions to read inputs, sum up the ones and tens place of inputted integers, and compute the average of input integers. Why can't I get more than one input that is a positive integer? The program runs after one input that is within the limits of integers that are valid.
#include <stdio.h>
int read_data(int Ar[]);
void comp_sums(int Ar[], int size); // prototypes
double comp_avg(int Ar[], int size);
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar);
comp_sums(Ar, size);
avg = comp_avg(Ar, size);
printf("The average of the integers in the array: %lf\n", avg);
}
int read_data(int Ar[]) // reads inputted integers, stores in array
{
int flag;
char ch;
int i,j, num;
flag = 1;
i = 0;
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
return i;
}
}
void comp_sums(int Ar[], int size) /* computes sum of ones and tens place of the inputted integers into the array*/
{
int i, j;
int sum_ones, sum_tens;
sum_ones = 0;
sum_tens = 0;
for (i = 0; i < size; i++) {
sum_ones += Ar[i] % 10;
j = Ar[i] / 10;
sum_tens += j % 10;
}
printf("The sum of the ones is: %d\n", sum_ones);
printf("The sum of the tens is: %d\n", sum_tens);
}
double comp_avg(int Ar[], int size) // computes average of integers
{
int i, sum;
double avg;
sum = 0;
for (i = 0; i < size; i++) {
sum += Ar[i];
}
avg = (double)size / sum;
return avg;
}
When you take an array as an argument, you have to take the length as well,
because you have to check if you are reading/writing out of bounds. Forget for a
second that the return is at that incorrect position, the user can input more
values than the array can hold and you are doing nothing to prevent the buffer overflow.
So to fix your read_data function:
int read_data(int Ar[], size_t len)
{
if(Ar == NULL || len == 0)
return 0;
int i = 0, j, num;
// imortant to check the bounds
while (i < len) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
break;
} else {
Ar[i] = num;
i++;
}
}
return i;
}
I removed the flag bit because if num >=100, you would be ending the loop
anyway, so it's much simpler to do a break. Also the intention is more clearer.
Now you can call it:
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar, sizeof Ar / sizeof *Ar);
...
}
The problem is that you call return inside the whileloop. So as soon as you get a valid number, you'll return from the function.
Move it outside the loop. Like:
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
// return i; Incorrect
}
return i; // Correct
I want to write a program that reads 10 int values from the user and swaps the largest and smallest numbers on the first and second values, then the rest of the numbers should be in the order.
Please check the code and help me what the wrong is.
For instance:
1
9
4
5
6
7
8
2
4
5
New order should be 9 1 4 5 6 7 8 2 4 5
#include <stdio.h>
int main() {
int a[10],i,min,max=0,pos=0;
printf("Please enter 10 int values :\n");
do{
scanf("%d", &a[pos++]);
} while (pos<10);
for (i=0; i<10;i++) {
printf("%i\n",a[i]);
if (max<a[i])
{
max=a[i];
}
if (min>a[i])
{
min=a[i];
}
for (i=0;i<10;i++) {
if (a[i]==max)
a[i]=max;
if (a[i] == min) a[i] = min;
}
printf("The new order is : %d %d %d ", max, min, ...);
return 0;
}
EDIT:
It is the new form
#include <stdio.h>
int main() {
int a[10],i,pos,temp,min = 0,max = 0;
printf("Please enter 10 int values :\n");
do {
scanf("%d", &a[pos++]);
} while (pos < 10);
for ( =1; i<10;i++) {
if (a[i]>a[max])
{
max=i;
}
if (a[i]<a[min])
{
min=i;
}
}
temp=a[max];
a[max]=a[min];
a[min]=temp;
printf("%d %d",a[max],a[min]);
for (i=0;i<10;i++){
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
return 0;
}
As others have noted, your code does not properly identify the maximum and minimum values in the array because you are writing min and max back into the array instead of the other way around.
Since you want to swap these values, what you actually want are the indices of the min and max values of the array, and swap those.
It is best to break this code into functions instead of having everything in main. Here is a solution that will do what you want:
#include <stdio.h>
int indexofmax(int *data, int len)
{
int max = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]>data[max]) max = i;
}
return max;
}
int indexofmin(int *data, int len)
{
int min = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]<data[min]) min = i;
}
return min;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
// user enters in 10 ints...
int max = indexofmax(a, 10);
int min = indexofmin(a, 10);
int i;
swap(&a[min], &a[max]);
for(i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
return 0;
}
This initialization min=0,max=0 is not right.
Instead have min = INT_MAX and max = INT_MIN.
By setting min=0, you would never get the lowest number in the array if it is greater than 0.
Similarly by setting max=0, you would never get the greatest number in the array if it is lower than 0.
You are gaining nothing by this code:
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
It is evident that this loop
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
does not make sense.
Moreover variable min is not initialized while variable max is initialized incorrectly.
int a[10],i,min,max=0,pos=0;
For example the array can contain all negative elements. In this case you will get incorrect value of the maximum equal to 0.
And I do not see where the elements are moved to the right to place the maximum and the minimum to the first two positions of the array.
If I have understood correctly then what you need is something like the following. To move the elements you could use standard function memmove declared in header <string.h>. However it seems you are learning loops.
#include <stdio.h>
#define N 10
int main( void )
{
int a[N] = { 4, 5, 9, 6, 7, 1, 8, 2, 4, 5 };
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
size_t min = 0;
size_t max = 0;
for (size_t i = 1; i < N; i++)
{
if (a[max] < a[i])
{
max = i;
}
else if (a[i] < a[min])
{
min = i;
}
}
if (max != min)
{
int min_value = a[min];
int max_value = a[max];
size_t j = N;
for (size_t i = N; i != 0; --i)
{
if (i - 1 != min && i - 1 != max)
{
if (i != j)
{
a[j - 1] = a[i - 1];
}
--j;
}
}
a[--j] = min_value;
a[--j] = max_value;
}
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
}
The program output is
4 5 9 6 7 1 8 2 4 5
9 1 4 5 6 7 8 2 4 5
You're not actually altering the array.
In the second loop, you say "if the current element is the max, set it to the max". In other words, set it to its current value. Similarly for the min.
What you want is to swap those assignments.
if(a[i]==max) a[i]=min;
if(a[i]==min) a[i]=max;
Also, your initial values for min and max are no good. min is unitialized, so its initial value is undefined. You should initialize min to a very large value, and similarly max should be initialized to a very small (i.e. large negative) value.
A better way to do this would be to keep track of the index of the largest and smallest values. These you can initialize to 0. Then you can check a[i] > a[max] and a[i] < a[min]. Then you print the values at indexes min and max, then loop through the list and print the others.
int i, temp, min=0, max=0;
for (i=1; i<10; i++) {
if (a[i] > a[max]) max = i;
if (a[i] < a[min]) min = i;
}
printf("%d %d ", a[max], a[min]);
for (i=0; i<10; i++) {
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
Just keep it nice and simple, like this:
#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 10
int find_biggest(int A[], size_t n);
int find_smallest(int A[], size_t n);
void print_array(int A[], size_t n);
void int_swap(int *a, int *b);
int
main(void) {
int array[MAXNUM], i, smallest, biggest;
printf("Please enter 10 int values:\n");
for (i = 0; i < MAXNUM; i++) {
if (scanf("%d", &array[i]) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
}
printf("Before: ");
print_array(array, MAXNUM);
smallest = find_smallest(array, MAXNUM);
biggest = find_biggest(array, MAXNUM);
int_swap(&array[smallest], &array[biggest]);
printf("After: ");
print_array(array, MAXNUM);
return 0;
}
int
find_biggest(int A[], size_t n) {
int biggest, i, idx_loc;
biggest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] > biggest) {
biggest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
int
find_smallest(int A[], size_t n) {
int smallest, i, idx_loc;
smallest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] < smallest) {
smallest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
void
print_array(int A[], size_t n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void
int_swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}