c program for smallest and second smallest in array - c

#include <stdio.h>
#include <string.h>
void main()
{
int smallest, secondsmallest;
int array[100], size, i;
printf("\n How many elements do you want to enter: ");
scanf("%d", &size);
printf("\nEnter %d elements: ", size);
for (i = 0 ; i < size; i++)
scanf("%d", &array[i]);
if (array[0] < array[1]) {
smallest = array[0];
secondsmallest = array[1];
}
else {
smallest = array[1];
secondsmallest = array[0];
}
for (i = 2; i < size; i++) {
if (array[i] < smallest) {
secondsmallest = smallest;
smallest = array[i];
}
else if (array[i] < secondsmallest) {
secondsmallest = array[i];
}
}
printf(" \nSecond smallest element is %d", secondsmallest);
printf(" \n smallest element is %d", smallest);
}
input:0 0 1 2
output:smallest is 0, second smallest is 0
i want to get 0,1 as output.i do not want to use sorting here.
how can i improve my code.

You are not handling the case of duplicate number. So I have modified your code. Please try this and let me know.
#include <stdio.h>
#include <string.h>
void main()
{
int smallest, secondsmallest;
int array[100], size, i;
printf("\n How many elements do you want to enter: ");
scanf("%d", &size);
printf("\nEnter %d elements: ", size);
for (i = 0 ; i < size; i++)
scanf("%d", &array[i]);
if (array[0] < array[1]) {
smallest = array[0];
secondsmallest = array[1];
}
else {
smallest = array[1];
secondsmallest = array[0];
}
for (i = 2; i < size; i++) {
if (array[i] < smallest) {
secondsmallest = smallest;
smallest = array[i];
}
else if (smallest == secondsmallest){
smallest = secondsmallest;
secondsmallest = array[i];
}
else if (array[i] < secondsmallest && array[i] > smallest) {
secondsmallest = array[i];
}
}
printf(" \nSecond smallest element is %d\n", secondsmallest);
printf(" \n smallest element is %d\n", smallest);
}

Related

printing the largest value in array

I was having a trouble regarding to printing out the largest number in array in c language and i don't know how to do it while using loop. Please help me thanks
here is my code
#include <stdio.h>
void main() {
int Lnum, size;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for (int i = 0; i < size; i++) {
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for (int i = size - 1; i >= 0; i--) {
printf("%d ", nums[i]);
}
for (int a = 0; a < size; a++) {
for (int i = 0; i < size; i++) {
if (nums[a] > nums[i]) {
Lnum = nums[a];
}
}
}
printf("\nLargest element = %d", Lnum);
}
The algorithm for determining the largest element in an array goes as follows.
Use the value of the first array element as a start value for the biggest number.
Go over the rest of the array and check for each element if it is a bigger number.
When a bigger number is found use the bigger number for further comparisons.
#include<stdio.h>
void main(){
int Lnum, size;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for(int i=0; i<size; i++){
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for(int i=size-1; i>=0; i--){
printf("%d ", nums[i]);
}
Lnum = nums[0]; // Assume first element to be the largest element
for(int a=1; a<size; a++){ // start loop with second element
if(Lnum < nums[a]) { // check if current element is larger
Lnum = nums[a]; // found larger element, it is now the largest element of all inspected element
}
}
printf("\nLargest element = %d", Lnum);
}
Output:
Enter the size: 3
1 2 3
Reversed = 3 2 1
Largest element = 3
...Program finished with exit code 0

Sorting an array with duplicate values without modifying the elements, without using secondary array or without using any inbuilt function

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;
}

Finding MAX and MIN of random numbers

I'm writing a program where the user enters numbers and the program will find MAX and MIN and the position of these numbers. I want to give the user a choice for the program to fill in the numbers for him using rand().
It's working almost perfectly: the program will find the MAX number with the position but the problem occurs when printing MIN number with position -- it always prints number 8 and position 1.
Where is the problem?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct elementposition {
int min;
int max;
int positionMax;
int positionMin;
} elementposition;
int main() {
struct elementposition minmax;
srand(time(NULL));
int a[500], i;
int c = sizeof(a) / sizeof(a[0]);
char y;
printf("How many numbers you want to enter: ");
scanf("%d", &c);
minmax.positionMax = minmax.positionMin = 0;
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c", &y);
if (y == 'Y' || y == 'y') {
for (i = 0; i < c; i++) {
a[i] = rand() % 10000 + 1;
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
for (i = 0; i < c; i++) {
printf("Number #%d: %d\n", i + 1, a[i]);
}
} else {
printf("------------------------------------ \n");
printf("Enter (%d) numbers: \n", c);
scanf("%d", &a[0]);
minmax.max = minmax.min = a[0];
for (i = 1; i < c; i++) {
scanf("%d", &a[i]);
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
}
printf("\nMax number is %d, number position %d. \n", minmax.max, minmax.positionMax + 1);
printf("Min number is %d, number position %d. \n", minmax.min, minmax.positionMin + 1);
printf("------------------------------------ \n");
getch();
return 0;
}
You never initialize minmax.min nor minmax.max in the random case. The code has undefined behavior because it depends on uninitialized values which may be anything, including trap values on some rare architectures.
You should separate the input/generation phase from the scanning phase and use a common loop for that. Also check that c is positive and does not exceed the length of the array.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
typedef struct elementposition {
int min;
int max;
int positionMax;
int positionMin;
} elementposition;
int main() {
struct elementposition minmax;
int a[500];
int i, count, len = sizeof(a) / sizeof(a[0]);
char y = 'y';
printf("How many numbers you want to enter: ");
if (scanf("%d", &count) != 1 || count < 1 || count > len) {
printf("invalid count\n");
return 1;
}
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c", &y);
if (y == 'Y' || y == 'y') {
srand(time(NULL));
for (i = 0; i < count; i++) {
a[i] = rand() % 10000 + 1;
printf("Number #%d: %d\n", i + 1, a[i]);
}
} else {
printf("Enter (%d) numbers:\n", c);
for (i = 0; i < count; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
}
minmax.positionMax = minmax.positionMin = 0;
minmax.max = minmax.min = a[0];
for (i = 1; i < count; i++) {
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
printf("------------------------------------\n");
printf("Max number is %d, number position %d.\n", minmax.max, minmax.positionMax + 1);
printf("Min number is %d, number position %d.\n", minmax.min, minmax.positionMin + 1);
printf("------------------------------------\n");
getch();
return 0;
}
You use minmax.min and minmax.max before initializing them. Here the problem for finding the min is probably that the minmax.min happens to initialy contain the value 8 and that all the values are greater.
The common way is to initialize the min to the highest possible value and max to the lowest one. As you use int values:
struct elementposition minmax = { INT_MAX, INT_MIN };
should be enough.

Finding pairs in an array that are equal to an input value

I have to find out if there is any pair of i,j such that array[i]^2 + array[j]^2 == x^2
.
If there are such pairs, I need to print all such (i,j). Otherwise, print “There are no such pairs”.
#include <stdio.h>
int main(){
int size=10, i, x,j;
int Array[size];
printf("What is the value of x:");
scanf("%d",&x);
for(i=0;i<size;i++){
printf("Enter array value :");
scanf("%d",&Array[i]);
}
for(i=0;i<size;){
for(j=i+1;j<size;j++)
if((Array[i]*Array[i])+(Array[j]*Array[j])==x*x) //how do I complete this for loop?
}
return 0;
}
Yo're almost there, why weren't you incrementing the value of i? Keep a counter to count the matched pairs, then print those or if nothing is found print whatever you want.
#include <stdio.h>
int main() {
int size = 10, i, x, j;
int Array[size];
printf("What is the value of x:");
scanf("%d", &x);
for (i = 0; i < size; i++) {
printf("Enter array value :");
scanf("%d", &Array[i]);
}
int counter = 0;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++)
if ((Array[i] * Array[i]) + (Array[j] * Array[j]) == x * x) {
printf("%d %d\n", Array[i], Array[j]);
counter++;
}
}
if (!counter) {
printf("There are no such pairs\n");
}
return 0;
}

Sum and get the average of the values in the array

Sum and get the average of the values in the array, and stop to ask a number when the sum exceeds 10,000.I need to clear it with an example of these conditions.
The language fit that need the example is in C
my code
```
#include <stdio.h>
int main()
{
int array[10];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;
printf ("Enter the value of N \n");
scanf("%d", &num);
printf("Enter %d numbers (negative, positve and zero) \n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array elements \n");
for (i = 0; i < num; i++)
{
printf("%+3d\n", array[i]);
}
for (i = 0; i < num; i++)
{
if (array[i] < 0)
{
negative_sum = negative_sum + array[i];
}
else if (array[i] > 0)
{
positive_sum = positive_sum + array[i];
}
else if (array[i] == 0)
{
;
}
total = total + array[i] ;
}
average = total / num;
printf("\n Sum of all negative numbers = %d\n", negative_sum);
printf("Sum of all positive numbers = %d\n", positive_sum);
printf("\n Average of all input numbers = %.2f\n", average);
}
```
Answer of your Question
#include <stdio.h>
int main()
{
int array[10];
int num, negative_sum = 0, positive_sum = 0,j;
static int i=0;
float total = 0.0, average;
label:
j=i;
printf ("Enter the value of N \n");
scanf("%d", &num);
printf("Enter %d numbers (negative, positve and zero) \n", num);
for (i; i < (j+num); i++)
{
scanf("%d", &array[i]);
}
i=j;
printf("Input array elements \n");
for (i; i < (j+num); i++)
{
printf("%d\n", array[i]);
}
i=j;
for (i; i < (j+num); i++)
{
if (array[i] < 0)
{
negative_sum = negative_sum + array[i];
}
else if (array[i] > 0)
{
positive_sum = positive_sum + array[i];
}
else if (array[i] == 0)
{
;
}
total = total + (float)array[i] ;
}
average = total / num;
printf("\n Sum of all negative numbers = %d\n", negative_sum);
printf("Sum of all positive numbers = %d\n", positive_sum);
printf("\n Average of all input numbers = %.2f\n", average);
if(total<10000)
{
printf("Total is less than 10000 and Now total is : %.2f\n",total);
goto label;
}}
it is the answer of your question.program will run when your total is exceed upto 10000.

Resources