Hi I need help please i need to fix this code so it count the value only once
for exmaple
input:
25
38 25 36 4 1 1 10 37 45 21 37 42 21 1 50 9 50 42 6 39 10 14 17 11 20
10
36 42 2 15 28 42 3 23 8 50
output:
4
the answer here should be 4 not 7.
#include <stdio.h>
int main()
{
int n, m, count = 0;
int array[1000];
int subarray[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d", &subarray[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (array[i] == subarray[j])
count++;
}
}
printf("%d\n", count);
}
Possible solution, using functions and qsort.
(untested code)
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int cmpfunc (const void * a, const void * b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
int main() {
int n, m, count = 0;
int array[1000];
int subarray[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
qsort(array, n, sizeof(int), cmpfunc); // O(n lg n)
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &subarray[i]);
int result = binarySearch(arr, 0, n - 1, x); // O(lg n)
if (result != -1)
count++;
} // O(m lg n)
printf("%d\n", count);
}
You need to keep track of the matched values in third array as following and
check if the new value is found before or not
#include <stdio.h>
int main()
{
int n, m, count = 0;
int array[1000];
int subarray[1000];
int result[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d", &subarray[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (array[i] == subarray[j]){
int isFound=0;
for(int k=0;k<count;k++){
if(result[k]==array[i])
isFound=1;
}
if(isFound==0){
result[count]==array[i];
count++;
}
}
}
}
printf("%d\n", count);
}
I use a boolean variable to check if the elements of array 1 exist in the array 2 ,if not ,i will copied it to array 3
#include <stdio.h>
#include <stdbool.h>//header how found the booleen variable
int main()
{
int n,m;
do
{
printf("Give me the length of array 1 :");
scanf("%d",&n);
}while(n<1);
int T1[n];//declaration of Array 1
do
{
printf("Give me the length of array 2 :");
scanf("%d",&m);
}while(m<1);
int T2[m];//declaration of Array 2
printf("The fill of Array 1:\n\n");
for(int i=0;i<n;i++)
{
scanf("%d",&T1[i]);
}
printf("The fill of Array 2:\n\n");
for(int j=0;j<m;j++)
{
scanf("%d",&T2[j]);
}
int T3[n+m];//declaration of Array 3
bool found=false;//declaration of booleen variable
int k=0;
for(int i=0;i<n;i++)
{found=false;
for(int j=0;j<m;j++)
{
if(T1[i]==T2[j])
{
found=true;
}
}
if(found==true)
{
T3[k]=T1[i];
k++;
}
}
printf("\nThe number of elment duplicate is :%d\n",k);
}
so it count the value only once
With minimal impact to OP's code and without re-ordering input:
Check if the subarray[] value already occurred within itself.
When subarray[]/array[] values match, quit looking.
for (int j = 0; j < m; j++) {
bool unique_subarray_value = true;
for (int earlier = 0; earlier < j; earlier++) {
if (subarray[earlier] == subarray[j])
unique_subarray_value = false;
break;
}
}
if (unique_subarray_value) {
for (int i = 0; i < n; i++) {
if (array[i] == subarray[j]) {
count++;
break;
}
}
}
}
A fast approach would sort the arrays and then walk them
// Pseudo code
sort array[n] with qsort()
sort subarray[m] with qsort()
// walk the arrays looking for matches
i = 0;
j = 0;
while (i < n && j < m) {
if (array[i] == subarray[j]) {
count++;
while (i + 1 < n && array[i] == array[i+1]) i++;
while (j + 1 < m && subarray[j] == subarray[j+1]) j++;
}
if (array[i] < subarray[j]) i++;
else j++;
}
Related
I want to store elements of maximum and minimum frequency in the arr2 array if there are more than one element of same frequency then both the elements should be stored ? But it is showing wrong results and i am not able to find what is the err. Can anyone help me with this. Any kind of help would be greatly appreciated.
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int arr2[n];
int prevcount = 0;
int k = 0;
// for finding max element
for (int i = 0; i < n; i++)
{
int count = 0;
//counting the number of times it has occured
for (int j = 0; j < n; j++)
{
if (arr[i] == arr[j])
{
count++;
}
}
// checking if the same element was not there in the new array
for (int i = 0; i < k; i++)
{
if (arr[i] == arr[k])
{
goto nextit;
}
}
//it will update the kth element if the count is greater than the prev count
if (prevcount < count)
{
arr2[k] = arr[i];
}
//if these both are same but the number is different then will iterate k by 1 and store that element as well
else if (prevcount == count)
{
k++;
arr2[k] = arr[i];
}
prevcount = count;
nextit:
}
// for finding min element
prevcount = 1000;
for (int i = 0; i < n; i++)
{
int count = 0;
for (int j = 0; j < n; j++)
{
if (arr[i] == arr[j])
{
count++;
}
}
// checking if the same element was not there in the new array if there is then go to the next iteration
for (int i = 0; i < k; i++)
{
if (arr[i] == arr[k])
{
goto nextit2;
}
}
if (prevcount > count)
{
arr2[k] = arr[i];
}
else if (prevcount == count)
{
k++;
arr2[k] = arr[i];
}
prevcount = count;
nextit2:
}
for (int i = 0; i < k; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
As #SparKot suggests, sorting the array makes the problem simple. Would you please try:
#include <stdio.h>
#include <stdlib.h>
// compare values numerically
int numeric(const void *a, const void *b)
{
return (*(int *)a < *(int *)b) ? -1 : (*(int *)a > *(int *)b);
}
int main()
{
int n, i, j;
int *arr; // input array
int *count; // count frequency: initialized to 0's by calloc
int min = 0; // minimum occurrences
int max = 0; // maximum occurrences
scanf("%d", &n);
if (NULL == (arr = malloc(n * sizeof(int)))) {
perror("malloc");
exit(1);
}
if (NULL == (count = calloc(n, sizeof(int)))) {
perror("calloc");
exit(1);
}
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
qsort(arr, n, sizeof(int), numeric);
// count the length of sequence of the same numbers
for (i = 0; i < n; i++) {
for (j = 0; i + j < n && arr[i] == arr[i + j]; j++) {
;
}
count[i] = j; // i'th element has length j
i += j - 1; // jump to next number
}
// find minimum and maximum frequencies
for (i = 0; i < n; i++) {
if (count[i]) {
if (min == 0 || count[i] < min) min = count[i];
if (max == 0 || count[i] > max) max = count[i];
}
}
// report the result
for (i = 0; i < n; i++) {
if (count[i] == min) {
printf("min frequency %d value %d\n", count[i], arr[i]);
}
if (count[i] == max) {
printf("max frequency %d value %d\n", count[i], arr[i]);
}
}
return 0;
}
Sample input (n=10):
6
1
2
5
1
2
3
1
3
6
Output:
max frequency 3 value 1
min frequency 1 value 5
So as the question says i am just trying to sort an array with duplicate values.
The array is sorted properly but problem arises when a duplicate value is given to the array
O/P:without duplicate
Enter the size of the array : 5
Enter the 5 elements
7 3 4 8 1
After sorting: 1 3 4 7 8
Original array value 7 3 4 8 1
O/P: with duplicates
5 3 1 1 4
After sorting: 1 3 4 1 3
Original array value 5 3 1 1 4
#include <stdio.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, temp, largest = arr[0], smallest = arr[0];
for( i = 1 ; i < size ; i++ )
{
if(arr[i] > largest)
{
largest = arr[i];
}
if(arr[i] < smallest)
{
smallest = arr[i];
}
}
printf("After sorting: ");
for(i = 0; i < size; i++)
{
temp = largest;
printf("%d ", smallest);
for(k = i + 1; k < size; k++)
{
if(arr[i] == arr[k])
{
smallest = arr[i];
break;
}
for(j = 0; j < size; j++)
{
if(arr[j] > smallest && arr[j] < temp)
{
temp = arr[j];
}
}
smallest = temp;
}
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ", arr[i]);
}
}
int main()
{
int size, i;
printf("Enter the size of the array : ");
scanf("%d", &size);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
print_sort(arr, size);
}
I understand that it is a specific exercise (homework ?), with no possibility to modify the array not to use an additional array.
This implies that classical sorting algorithms cannot work.
Iteratively searching for the minimum is a possible solution, even if not efficient O(n^2).
To cope with duplicates, it it necessary not only to memorize the current minimum, but also its position.
This is a possible implementation.
#include <stdio.h>
#include <stdlib.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, largest = arr[0], smallest = arr[0];
int i_smallest = 0;
for (i = 1; i < size; i++ ) {
if (arr[i] > largest) {
largest = arr[i];
}
if(arr[i] < smallest) {
smallest = arr[i];
i_smallest = i;
}
}
printf("After sorting: ");
for (i = 0; i < size; i++) {
int temp = largest + 1;
int i_temp = -1;
printf("%d ", smallest);
if (i == size-1) break;
for (k = 0; k < size; k++) {
if (arr[k] < smallest) continue;
if (arr[k] == smallest) {
if (k <= i_smallest) continue;
i_temp = k;
temp = smallest;
break;
}
if (arr[k] < temp) {
temp = arr[k];
i_temp = k;
}
}
smallest = temp;
i_smallest = i_temp;
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ",arr[i]);
}
}
int main(void) {
int size, i;
printf("Enter the size of the array : ");
if (scanf("%d", &size) != 1) exit(1);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++) {
if (scanf("%d", &arr[i]) != 1) exit(1);
}
print_sort(arr, size);
return 0;
}
Maybe it is easier to insert each read value directly into the sorted Array. So you don't have to sort the array afterwards.
If you want to do it this way, geeksforgeeks.org has nice examples also for C which I already used (https://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/).
// C program to implement insert operation in
// an sorted array.
#include <stdio.h>
// Inserts a key in arr[] of given capacity. n is current
// size of arr[]. This function returns n+1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capacity
if (n >= capacity)
return n;
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
return (n + 1);
}
/* Driver program to test above function */
int main()
{
int arr[20] = { 12, 16, 20, 40, 50, 70 };
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
printf("\nBefore Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
// Inserting key
n = insertSorted(arr, n, key, capacity);
printf("\nAfter Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
I've been trying to sort columns in a matrix (the dimensions are m,n <= 10) via the lexicographical order (if the columns share the same element, then we compare the elements in the row beneath etc.) with some additional conditions. I need to use functions to print the matrix, input random integers up to 5 as its elements and finally arrange the matrix. I think I got the printing and random inputs correctly but I can't figure out the sorting. Plus I can't use global variables which I have no idea how to do, since I haven't been shown. An example matrix would be :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m, n;
int mat[10][10];
void print_matrix()
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
for (k = i + 1; k < m; ++k)
{
if (mat[i][j] < mat[k][j])
{
a = mat[i][j];
mat[i][j] = mat[k][j];
mat[k][j] = a;
}
}
}
}
}
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int(mat[m][n]);
print_matrix(mat[m][n]);
arrange(mat[m][n]);
print_matrix(mat[m][n]);
return 0;
}
Try this solution(will work for input 0-8 only), also used global variables:
There have multiple solutions. but is the easiest one.
I have converted each of the columns as an integer value. then bubble sorted the integers. After sorting. I have then converted the integer value to digits. (You have to know how to convert individual digits to multiple digit integer and multiple digit integers to single-digit.
Note I have added one(1) with each digit. Because the input can be zero(0). if you convert 0 0 2 1 to an integer will be only 21. the first two digits lost. So I have added 1. so 0 0 2 1 will be converted to 1132. I have done (added 1) for each input(deducted 1 after sorting). so it will not affect other inputs. Be careful input have to be from(0 to 8)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m, n;
int mat[10][10];
int generatedNumber[10];
void print_matrix()
{
printf("The matrix is:\n");
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
int number = 0;
for (i = 0; i < m; ++i)
{
number = number * 10 + mat[i][j] + 1;///Adding one for avoiding zero(0)
}
generatedNumber[j] = number;
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( generatedNumber[j] > generatedNumber[j+1])
{
// swap the elements
int temp = generatedNumber[j];
generatedNumber[j] = generatedNumber[j+1];
generatedNumber[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)///columwise
{
int generatedColumnvalue = generatedNumber[i];
for(j = m -1; j>= 0; j--)///row wise and fro last vaue to first
{
mat[j][i] = (generatedColumnvalue%10)-1;///removing extra added 1
generatedColumnvalue/=10;
}
}
}
int main()
{
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int();
print_matrix();
arrange();
print_matrix();
return 0;
}
I have written a piece of code below, that ask a user input a number N (3 < N < 1.000.000) odd and count the number of prime number pairs whose sum is equal to N. That code works, but I need to optmize it to make more efficient. When the user inputs a number, I count the number of primes up to this number and store each prime number in a vector, and after that count the number of prime number pairs whose sum is equal to this input.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void seleciona_primos (int *vet, int n, int raiz){
int i, j;
vet[2] = 2;
for(i=3; i<=n; i+=2){
vet[i] = i;
}
for (i=3; i<= raiz; i+=2){
if(vet[i]!=0){
for(j=3; j<=n; j+=2){
if ((vet[i]!=vet[j]) && (vet[j]%vet[i] == 0)){
vet[j]=0;
}
}
}
}
}
int conta_pares (int *vet, int n){
int i, j, count=0;
for (i=3; i<=n; i+=2){
if(vet[i]!=0){
for(j=3; j<=n/2; j+=2){
if((vet[j]!=0) && (vet[i] + vet[j] == n)&& (vet[i]!=0)){
//printf("%d ", vet[i]);
//printf("%d\n", vet[j]);
count++;
vet[i] = 0;
}
}
}
}
if(vet[n-2]!=0){
count++;
}
return count;
}
int main()
{
int *vet, n, raiz, i , count;
scanf("%d", &n);
vet = (int *) calloc((n+1), sizeof(int));
raiz = floor(sqrt(n));
seleciona_primos(vet, n, raiz);
count = conta_pares(vet, n);
printf("%d",count);
//for(i=3; i<=n; i+=2){
//if(vet[i]!=0){
//printf("%d\n", vet[i]);
//}
//}
return 0;
}
I make an array who countain the prime numbers from 2 to N(1 has only one divisors and 0 has infinites of divisors), and then I check if two numbers from the array equal to N
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool Prime(int);
int main()
{
long N;
do
{
printf("Give me the number of numbers :");
scanf("%ld",&N);
}while(N<=4||N>1000000);//N must be between 3 & 1000000
int prime[N];
int arr[N];
int j=0;
for(int i=2;i<N;i++)
{
if(Prime(i)==true)
{
prime[j]=i;
j++;
}
}
printf("\n\n");
for(int p=0;p<j-1;p++)
{
for(int q=p+1;q<j;q++)
{
if(N==prime[p]+prime[q])
{
printf("\n%d = %d + %d \n",N,prime[p],prime[q]);
}
}
}
printf("\n\n");
return 0;
}
bool Prime(int n)
{
for(int i=2;i<=(n/2);i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
Example :
Input : N =100;
Output :
100 = 3 + 97
100 = 11 + 89
100 = 17 + 83
100 = 29 + 71
100 = 41 + 59
100 = 47 + 53
Thank you for all suggestions!!
And after some research and tries, I have found the solution that follow bellow:
int isPrime(int x)
{
int i;
for(i = 2; i <= sqrt(x); i++)
{
if(x%i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int i, count = 0, n ;
scanf("%d", &n);
for(i = 3; i <= n/2 ; i+=2)
{
if(isPrime(i))
{
if((isPrime(n-i)))
{
count++;
}
}
}
if(isPrime(n-2))
{
count++;
}
printf("%d", count);
return 0;
}
I modified your code to optimize it, I have set two Boolean vectors one for 5 mod(6) prime numbers (vet1[i]=false corresponds to prime number 6 x i-1 es. i=1 corresponds to prime number 5=6 x 1-1) and one (vet2[i]corresponds to prime number 6 x i+1) for prime numbers 1 mod(6)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
void seleciona_primos (bool *vet1, bool *vet2,int n){
int i, i1,imax;
imax=(n-n%6)/6+1;
for (i=1; (6*i-1)*(6*i-1) <=n; i++){
if (vet1[i]==false){
for(int i1 = 6*i*i; i1 <= imax+2*i; i1 += (6*i-1)){
if(i1<imax)
vet1[i1]=true;
vet2[i1-2*i]=true;
}
}
if (vet2[i]==false){
for(int i1 = 6*i*i; i1 <= imax; i1 += (6*i+1)){
vet1[i1]=true;
if(i1<imax-2*i)
vet2[i1+2*i]=true;
}
}
}
}
int conta_pares (bool *vet1, bool *vet2, int n){
int i,imax, count=0,r6;
imax=(n-n%6)/6;
r6=n%6;
if (r6==0){
for (i=1; i<imax; i++){
if(vet1[i]== false && vet2[imax-i]== false)
count++;
}
}
if (r6==2){
for (i=1; i<imax; i++){
if(vet2[i]== false && vet2[imax-i]== false)
count++;
}
count=(count+count%2)/2;
}
if (r6==4){
for (i=1; i<=imax; i++){
if(vet1[i]== false && vet1[imax+1-i]== false)
count++;
}
count=(count+count%2)/2;
}
if (r6>0 && r6<3){
if (vet1[imax]==false)
count++;
}
if (r6>2 && r6<5){
if (vet2[imax]==false)
count++;
}
return count;
}
int main()
{
int n, i , count;
bool *vet1, *vet2;
scanf("%d", &n);
vet1 = (bool *) calloc((n-n%6)/6+2, sizeof(bool));
vet2 = (bool *) calloc((n-n%6)/6+2, sizeof(bool));
seleciona_primos(vet1,vet2, n);
count = conta_pares(vet1,vet2, n);
printf("%d",count);
free(vet1);
free(vet2);
return 0;
}
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;
}