Program to find largest and second largest number in array - c

I have searched many websites for this question. They are doing it by some different approach.
This code is just not giving output if I input first element of array as largest i.e. a[0].
I think some minor change is required.
can anyone please tell me?
#include <stdio.h>
int main() {
int a[10], n;
int largest1, largest2, i;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
largest1 = a[0];
for (i = 0; i < n; i++) {
if (a[i] > largest1) {
largest1 = a[i];
}
}
largest2 = a[0];
for (i = 1; i < n; i++) {
if (a[i] > largest2 && a[i] < largest1)
largest2 = a[i];
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}

(I'm going to ignore handling input, its just a distraction.)
The easy way is to sort it.
#include <stdlib.h>
#include <stdio.h>
int cmp_int( const void *a, const void *b ) {
return *(int*)a - *(int*)b;
}
int main() {
int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
const int n = sizeof(a) / sizeof(a[0]);
qsort(a, n, sizeof(a[0]), cmp_int);
printf("%d %d\n", a[n-1], a[n-2]);
}
But that isn't the most efficient because it's O(n log n), meaning as the array gets bigger the number of comparisons gets bigger faster. Not too fast, slower than exponential, but we can do better.
We can do it in O(n) or "linear time" meaning as the array gets bigger the number of comparisons grows at the same rate.
Loop through the array tracking the max, that's the usual way to find the max. When you find a new max, the old max becomes the 2nd highest number.
Instead of having a second loop to find the 2nd highest number, throw in a special case for running into the 2nd highest number.
#include <stdio.h>
#include <limits.h>
int main() {
int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
// This trick to get the size of an array only works on stack allocated arrays.
const int n = sizeof(a) / sizeof(a[0]);
// Initialize them to the smallest possible integer.
// This avoids having to special case the first elements.
int max = INT_MIN;
int second_max = INT_MIN;
for( int i = 0; i < n; i++ ) {
// Is it the max?
if( a[i] > max ) {
// Make the old max the new 2nd max.
second_max = max;
// This is the new max.
max = a[i];
}
// It's not the max, is it the 2nd max?
else if( a[i] > second_max ) {
second_max = a[i];
}
}
printf("max: %d, second_max: %d\n", max, second_max);
}
There might be a more elegant way to do it, but that will do, at most, 2n comparisons. At best it will do n.
Note that there's an open question of what to do with { 1, 2, 3, 3 }. Should that return 3, 3 or 2, 3? I'll leave that to you to decide and adjust accordingly.

The problem with your code is a logic problem (which is what most coding is about). If the largest number is first then it gets the second largest number wrong ... why?
Well, look at your logic for deciding on the second largest number. You first set it to be equal to the first element in the array and then you go through the array and change the index if the element is greater than the current second largest number (which will never be true because we already set it to be the largest number!).
To solve it you can special case this: check if the largest number was the first and if so then set it to the second element (and then special case the issue of someone asking to find the highest two elements in a one element array, without reading past the end of an array.)
I think the method given in chqrlie's answer to do this all in one pass is best. And logical too: write a program to find the largest number. Second largest number, well that's just the one which was previously the largest!

You need to preserve the index of array members better as they are unique Here is a working code with few changes:
#include<stdio.h>
int main()
{
int a[10],n;
int largest1,largest2,i;
printf("enter number of elements you want in array");
scanf("%d",&n);
printf("enter elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest1=0;
for(i=0;i<n;i++)
{
if(a[i]>a[largest1])
{
largest1=i;
}
}
if(largest1!=0) // this condition to select another index than the largest
largest2=0;
else
largest2=n-1;
for(i=0;i<n && i != largest1 ;i++)
{
if(a[i]>a[largest2])
largest2=i;
}
printf("First and second largest number is %d and %d ",a[largest1],a[largest2]);
}
Note that when the array is of size 1 values will be the same.

The question is ambiguous: if the array may contain duplicate values, are you supposed to find the 2 largest distinct values or the two largest possibly identical values?
Your code seems to indicate you want the first approach, but you have a problem if the largest value is a[0]. You should use an extra boolean to keep track of whether you have found a different value yet.
You should also test the return value of the different scanf() calls and return 0 from main().
Here is a modified version:
#include <stdio.h>
int main(void) {
int a[10], n, i;
int largest1, largest2, has_largest2;
printf("enter number of elements you want in array: ");
if (scanf("%d", &n) != 1)
return 1;
if (n < 2) {
printf("need at least 2 elements\n");
return 1;
}
printf("enter elements: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("input error\n");
return 1;
}
}
largest1 = a[0];
for (i = 1; i < n; i++) {
if (a[i] > largest1) {
largest1 = a[i];
}
}
has_largest2 = largest2 = 0;
for (i = 0; i < n; i++) {
if (a[i] < largest1) {
if (!has_largest2) {
has_largest2 = 1;
largest2 = a[i];
} else
if (a[i] > largest2) {
largest2 = a[i];
}
}
}
if (has_largest2) {
printf("First and second largest number is %d and %d\n",
largest1, largest2);
} else {
printf("All values are identical to %d\n", largest1);
}
return 0;
}

You can do it best in one pass.
largest and largest2 are set to INT_MIN on entry.
Then step through the array. If largest is smaller than the number, largest2 becomes largest, then largest becomes the new number (or smaller than or equal if you want to allow duplicates). If largest is greater then the new number, test largest2.
Note that this algorithm scales to finding the top three or four in an array, before it become too cumbersome and it's better to just sort.

//I think its simple like
#include<stdio.h>
int main()
{
int a1[100],a2[100],i,t,l1,l2,n;
printf("Enter the number of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a1[i]);
}
l1=a1[0];
for(i=0;i<n;i++)
{
if(a1[i]>=l1)
{
l1=a1[i];
t=i;
}
}
for(i=0;i<(n-1);i++)
{
if(i==t)
{
continue;
}
else
{
a2[i]=a1[i];
}
}
l2=a2[0];
for(i=1;i<(n-1);i++)
{
if(a2[i]>=l2 && a2[i]<l1)
{
l2=a2[i];
}
}
printf("Second highest number is %d",l2);
return 0;
}

There is no need to use the Third loop to check the second largest number in the array. You can only use two loops(one for insertion and another is for checking.
Refer this code.
#include <stdio.h>
int main()
{
int a[10], n;
int i;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int largest1 = a[0],largest2 = a[0];
for (i = 0; i < n; i++)
{
if (a[i] > largest1)
{
largest2=largest1;
largest1 = a[i];
}
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}
Hope this code will work for you.
Enjoy Coding :)

Find your second largest number without using any String function:
int array[];//Input array
int firstLargest, secondLargest;
int minNumber = -1;//whatever smallest you want to add here
/*There should be more than two elements*/
if (array_size < 2)
{
printf("Array is too small");
return;
}
firstLargest = secondLargest = minNumber;
for (index = 0; index < array_size ; ++index)
{
//Largest number check
if (array[index] > first)
{
secondLargest = firstLargest;
firstLargest = array[index];
}
//It may not larger than first but can be larger than second number
else if (array[index] > secondLargest && array[index] != firstLargest)
{
secondLargest = array[index];
}
//Finally you got your answer
if (secondLargest == minNumber)
{
printf("No Second largest number");
}
else
{
printf("Second Largest Number is %d", secondLargest);
}

Here is an answer with a single for loop.
int array[] = { 10, 15, 13, 20, 21, 8, 6, 7, 9, 21, 23 };
const int count = sizeof(a) / sizeof(a[0]);
int lastMaxNumber = 0;
int maxNumber = 0;
for (int i = 0; i < count; i++) {
// Current number
int num = array[i];
// Find the minimum and maximum from (num, max)
int maxValue = (num > maxNumber) ? num : maxNumber;
int minValue = (num < maxNumber) ? num : maxNumber;
// If minValue is greater than lastMaxNumber, update the lastMaxNumber
if minValue > lastMaxNumber {
lastMaxNumber = minValue;
}
// Updating maxNumber
maxNumber = maxValue;
}
printf("%d", lastMaxNumber);

If you need to find the largest and second largest element in an existing array, see the answers above (Schwern's answer contains the approach I would've used).
However; needing to find the largest and second largest element in an existing array typically indicates a design flaw. Entire arrays don't magically appear - they come from somewhere, which means that the most efficient approach is to keep track of "current largest and current second largest" while the array is being created.
For example; for your original code the data is coming from the user; and by keeping track of "largest and second largest value that the user entered" inside of the loop that gets values from the user the overhead of tracking the information will be hidden by the time spent waiting for the user to press key/s, you no longer need to do a search afterwards while the user is waiting for results, and you no longer need an array at all.
It'd be like this:
int main() {
int largest1 = 0, largest2 = 0, i, temp;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &temp);
if(temp >= largest1) {
largest2 = largest1;
largest1 = temp;
} else if(temp > largest2) {
largest2 = temp;
}
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}

Try Out with this:
firstMax = arr[0];
for (int i = 0; i<n; i++) {
if (firstMax < arr[i] ) {
secondMax = firstMax;
firstMax = arr[i];
}
}

Although it can be done in one scan but to correct your own code , you must declare largest2 as int.Min as it prevents the largest2 holding the largest value intially.

#include<stdio.h>
int main()
{
int a[10];
int i,b,c;
printf("Enter ten values : \n");
for(i=0; i<10; i++)
{
scanf("%d",&a[i]);
}
b=a[0];
for(i=0; i<10; i++)
{
if(a[i]>b)
{
b=a[i];
}
else
{
b=b;
}
}
if(b==a[1])
{
c=a[2];
}
else
{
c=a[1];
}
for(i=0; i<10; i++)
{
if(a[i]>c && a[i]!=b)
{
c=a[i];
}
else if (b>c)
{
c=c;
}
}
printf("Largest number is %d\nSecond largest number is %d",b,c);
}

If you ever need to find the largest or smallest element in an array, try with bubble sort.
Bubble Sort works on simple concept of shifting the biggest element at the end in every pass it does (in case of increasing order). Since you need the first and second largest element in an array, 2 passes of bubble sort will do the trick. The last element will be the largest and the second last element will be second largest.
I'm providing you with the link that'll help you understand the bubble sort concept.
http://www.codeido.com/2010/10/bubblesort-written-in-c-with-example-step-by-step/
Hope it helps!!!

Related

prime number finding from array,c language [duplicate]

This program is supposed to print the first x prime numbers, but I noticed that it was printing some non-prime numbers, such as 27 or 35.
I've been looking at it for hours and nothing seems to pop up. So please, if you know what's wrong, tell me.
#include <stdio.h>
int main(){
int i=0, cont=2, prim=2, quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
while(i<quant){
if(prim%cont!=0 && (cont>1 && cont<prim)){
cont++;
}
else if(prim%cont==0 && (cont>1 && cont<prim)){
prim++;
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
return 0;
}
UPDATE
Wow, ok, so after 7 years people still stumble upon this question.
In the last 7 years my coding ability has improved somewhat, and now I see how inefficient this program was. Just in case anyone might be trying to find the solution for this and the stumble upon this, here are three solutions much easier and better, and why they work.
Solution 1:
This first solution is very inefficient too, but it works, and is pretty simple to understand. Basically what you have to do is check if each number up to the upper limit is prime or not. To do so, just check if it is divisible by any number up to its square root.
Why its squared root? Because the square root squared is equal to the number, which means that if the number was not divisible up to its square root, it won't be divisible by any number above it, as for it to be divisible by it, it needs to multiply by a smaller number. For example, the squared root of 36 is 6, and 36 is divisible by 9, as 9*4=36. But since 9 is above 6 (which is the squared root), the number that multiplied by 9 gives us 36 is below, and as such, we have already seen that it is not prime, as we have already checked that 36 is divisible by 4. This being said, if no number below the squared root of a number is a natural dividend of the number, than that number is prime.
#include <stdio.h>
int isPrime(int num) {
for (int i = 2; i*i <= num; i++) {
if (num%i==0) {
return 0;
}
}
return 1;
}
void getPrimes(int num) {
int cont = 0;
for (int i = 2; cont < num; i++) {
if (isPrime(i)==1) {
printf("%d\n", i);
cont++;
}
}
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
This is inefficient as we are checking if the number is divisible by numbers that won't influence (more on this in the next solution).
Solution 2:
In this second solution, which is more elegant in my opinion, we give use to the Fundamental Theorem of Arithmetic, which states that any number greater than 1 is either a prime number itself, or can be represented by factorizing into the multiplication of prime numbers. This means that if a number is divisible by a non prime number, it is also divisible by the prime numbers that make it up, and thus we only need to check if the number in question is divisible by smaller prime numbers than itself. For this purpose, we store the prime numbers in an array.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; i < cont; i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Solution 3:
This final solution is a mix of the two above. Solution 1 checked numbers that weren't prime, having redundancy, and the solution 2 checked numbers above the square root, which can never be a dividend if the smaller numbers aren't. In this solution, we check if the number is divisible only by prime numbers below the squared root.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; (i < cont && primes[i]*primes[i] <= current); i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Comparing the execution times of each algorithm for 100 prime numbers, we obtain the following results
Algorithm 1
Algorithm 2
Algorithm 3
0.048 ms
0.068 ms
0.039 ms
Comparing to the algorithm of the original post which takes 0.599 ms, every one of these new solutions is more efficient (the worst being around 10x better), and actually calculates the real values.
Try this
#include<stdio.h>
int prime(int n)
{
int i, j, len=1, brk=0;
int list[200]={2};
for(i=2; i<=n; i++)
{
for(j=0; j<len; j++)
{
if(i%list[j]==0){
brk=1;
break;
}
else
{
brk=0;
}
}
if(brk==0)
{
list[len]=i;
len++;
}
}
for(i=0; i<len; i++)
printf("%d ",list[i]);
}
main()
{
int i, n;
scanf("%d",&n);
prime(n);
}
#PKDOJ If the series is set within 30. You can go blindly with the logic below. But nothing above that series. Adding i%11 clears the 77 as well. Not efficient
if ((i % 2) && (i % 3) && (i % 5)&&(i%7)&&(i%11))
Code:
int count = 0, quant = 5, i, j;
int flag = 0;
for(prim = 2 ; count <= quant ; prim ++) {
flag = 0;
for(j = 2; j < prim/2; j++) {
if(prim % j == 0) {
flag = 1;
break;
}
}
if(flag == 0) {
printf("%d\n", prim);
count++;
}
}
Update your code as:
while(i<quant){
if(cont<prim) {
if(prim%cont!=0) {
cont++;
} else {
prim++;
cont = 2; // restart cont
}
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
Simple way is to find is: if a number is not divisible by 2,3 & 5, its a prime number.
#include <stdio.h>
int main()
{
int num = 35;
int i = 5;
printf("1 2 3 5");
while (i <= num)
{
if ((i % 2) && (i % 3) && (i % 5))
{
printf(" %d",i);
}
i++;
}
printf("\n");
return 0;
}

How to write a program to delete an element in an array using C language? [duplicate]

I wrote the following program to delete an array element entered by the user.
#include <stdio.h>
#include <conio.h>
void main() {
int j, i, a[100], n, key, l;
clrscr();
printf("Enter the number of elements:");
scanf("%d", &n);
printf("\nEnter the elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\nEnter the element to delete:");
scanf("%d", &key);
l = n; //Length of the array
for (i = 0; i < l; i++) {
if (a[i] == key) {
for (j = i; j < l; j++)
a[j] = a[j + 1];
l--; //Decreasing the length of the array
}
}
printf("\nThe new array is \n");
for (i = 0; i < l; i++)
printf("%d ", a[i]);
getch();
}
It works fine for most inputs but when the input is something like: 1 2 2 3 5 (here 2 repeats consecutively) and the element to be deleted is 2, the output is 1 2 3 5.
How can I modify the program such that all instances of the entered element is removed?
After l-- put i-- too as shown below
if(a[i]==key)
{
for(j=i;j<l;j++)
a[j]=a[j+1];
l--; //Decreasing the length of the array
i--; //check again from same index i
}
Other posters have given you 2 solutions ... I think understanding why it happens is good too :)
Let's take your example 1, 2, 2, 3, 5 and follow the code line by line
i = 0; /* first time through the loop; i "points" to 1 */
if (a[i] == 2) ... /* nope; next loop */
i = 1;
if (a[1] == 2) ... /* yes! let's go inside the if */
/* move all elements back
** and "decrease" array length */
/* array is now 1, 2, 3, 5 */
/* next loop */
i = 2;
if (a[i] == 2) ... /* nope; OH! Wait ...
** a[1] is the new 2 and it wasn't checked */
If you don't care about the order of the elements in the array, you can move the last element of the array into the newly formed gap (cunningly reducing the length of the array by one). This can be vastly more efficient than shunting the elements down: in computer science term this makes deleting an element O(1) rather than O(N).
a[i] = a[--l];
If your i index is looping over the array, you'll want to loop over this element again:
a[i--] = a[--l];
For example, to remove all elements '3' from an array of length 'l':
for (i = 0; i < l; ++i) {
if (a[i] == 3) {
a[i--] = a[--l];
}
}
If you do care about the order of the elements in the array, it's most efficient to use memmove rather than move elements by hand. It's designed to be used where the source and destination memory overlap.
memmove(a + i, a + i + 1, sizeof(a[0]) * (l - i - 1));
Change "if" to "while":
for(i=0;i<l;i++)
{
while (i<l && a[i]==key)
{
for(j=i;j<l;j++)
a[j]=a[j+1];
l--; //Decreasing the length of the array
}
}
use a new array.
int array[l];
int k=0;
for(i=0;i<l;i++)
{
if(a[i]!=key)
{
array[k]=a[i];
k++;
}
}
#include<stdio.h>
int main(){
int size;
int array[20];
int delete_pos;
int i;
printf("Enter the Size of the Array :");
scanf("%d",&size);
for(i=0;i<=size-1;i++){ //no of elements taken are 1 less than size of the array asked.
printf("\nEnter the element[%d] :",i+1);
scanf("%d",&array[i]);
}
printf("\nEnter the Position of the array to be deleted :");
scanf("%d",&delete_pos);
for(i=delete_pos-1;i<=size;i++){ //every element of the array is replaced by array on next position.
array[i]=array[i+1];}
size=size-1; // Reducing the size of the array as one element is deleted.
printf("Your new array is \n");
for(i=0;i<=size-1;i++){ //printing the entire new array.
printf("%d ",array[i]);
}
printf("\n\n");
return 0;
}
Your method with 2 nested for loops is too complicated. You can simple scan the array with an index i and copy all elements different from key with a different index len. The resulting array length is the final value of len.
Here is a modified version:
#include <stdio.h>
#include <conio.h>
int main(void) {
int a[100];
int i, n, key, len;
clrscr();
printf("Enter the number of elements: ");
if (scanf("%d", &n) != 1) {
printf("invalid input\n");
return 1;
}
if (n < 0 || n > 100) {
printf("invalid number of elements\n");
return 1;
}
printf("\nEnter the elements:\n");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
printf("\nEnter the element to delete: ");
if (scanf("%d", &key) != 1) {
printf("invalid input\n");
return 1;
}
for (i = len = 0; i < n; i++) {
if (a[i] != key)
a[len++] = a[i];
}
printf("\nThe new array is:\n");
for (i = 0; i < len; i++)
printf("%d ", a[i]);
printf("\n");
getch();
return 0;
}
Notes:
The prototype for main without arguments is int main(void) and it is considered good style to return 0 for success.
always test the return value of scanf(). This prevents many bugs and undefined behavior for invalid input. It also saves a lot of time looking in the wrong places when input was just invalid.
avoid naming a variable l as it looks too close to 1 in many fixed pitch fonts.
always terminate the program output with a newline.

C program to output the largest element of array with the index of the largest element of array

I'm taking my first ever programming class and most of it is self taught. So please bear with me.
After the users input numbers, such as 10, 20, 100, 3, 4 there should be an output to read
"the index of the largest elmeent in list1 array is _
The largest element in list1 array is 100" "
Here is my code so far. I know how to get the output of the largest array but not the first line or how to name my array. Thanks so much in advance.
#include<stdio.h>
int main()
{
int i;
float arr[5];
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf_s("%f", &arr[i]);
}
for (i = 1; i < 5; ++i)
{
if (arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
This code here will give you the biggest element is the array but it also changes the order in which the elements were entered. Instead of taking the biggest element to the 0th position of the array,you can simply use an integer to store the index of the biggest element.Your program can be modified like this :
#include<stdio.h>
int main()
{
int i,temp=0;
float arr[5];
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf_s("%f", &arr[i]);
}
for (i = 1; i < 5; ++i)
{
if (arr[temp] < arr[i])
temp=i;
}
printf("Largest element = %.2f", arr[temp]);
printf("Index = %d",temp);
return 0;
}
Hope the answer was useful.
Your approach to find the max element in an array is fine. But it alters the original array. If it okay with you, then go ahead with it, else if you would like to keep the array in tact as well as find the max element with the index, then check the code which I have attached below. If you intend to keep the methodology same, then just add a variable, which you should update as and when you find a higher number, as follows:
int max_index; //declare before
if (arr[0] < arr[i]) {
max_index = i;
arr[0] = arr[i];
}
If you are interested to keep the array unchanged and find out the max element with its index, the code would be as follows:
#include<stdio.h>
int main()
{
int i, max_index;
float arr[5], max;
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf("%f", &arr[i]);
}
max = arr[0];//start off assuming that the 1st element is the max
for (i = 0; i < 5; i++)//now compare it with the rest of the array, updataing the max all along
{
if (arr[i] > max) {
max = arr[i];
max_index = i;
}
}
printf("Largest element = %.2f at index %d", max, max_index);
return 0;
}
Hope this helps.
You know, that you can get the element if you know its index. This means, you can store the index of the "known biggest" element, and you can refer to the biggest element using the stored index.
int imax = 0;
for (i = 1; i < 5; ++i)
{
if (arr[imax] < arr[i])
imax = i;
}
printf("Largest element = %.2f at index %i\n", arr[imax], imax);
.
use this code in place of last loop

Finding the second largest element in array without sorting

I know about the single traversal method initialising two variables to INT_MIN. But my question is why do we initialise two variables to INT_MIN and also what is the purpose of INT_MIN here?
Why can't we initialise two variables to its first element like I have done in the code below? Because when I hand-checked the code manually, I found nothing wrong. So why doesn't the code run properly?
#include <stdio.h>
int main(void) {
int x[10];
int i, n;
int first = x[0];
int second = x[0];
printf("Input the size of array :");
scanf("%d", &n);
printf("Input %d elements in the array :\n", n);
for (i = 0; i < n; i++) {
printf("x[%d]: ", i);
scanf("%d", &x[i]);
}
for (i = 0; i < n; ++i) {
if (first < x[i]) {
second = first;
first = x[i];
} else
if (x[i] > second && x[i] != first) {
second = x[i];
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d", second);
return 0;
}
There are several problems in your code:
the array x is defined with a length of 10, but uninitialized when you set first and second to the value of its first element.
you do not test the return value of scanf(), leading to undefined behavior in case of input failure.
you do not test of n is in less or equal to 10 before reading values into x.
you need to special case n <= 0 as no values will be read into x.
Here is a modified version:
#include <stdio.h>
int main(void) {
int x[10];
int i, n, first, second;
printf("Input the size of array :");
if (scanf("%d", &n) != 1 || n < 0 || n > 10) {
printf("invalid input\n");
return 1;
}
if (n <= 0) {
first = second = 0;
} else {
printf("Input %d elements in the array:\n", n);
for (i = 0; i < n; i++) {
printf("x[%d]: ", i);
if (scanf("%d", &x[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
first = second = x[0];
for (i = 1; i < n; ++i) {
if (first < x[i]) {
second = first;
first = x[i];
} else
if (x[i] > second && x[i] != first) {
second = x[i];
}
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d\n", second);
return 0;
}
Regarding an alternative implementation where first and second are initialized to INT_MIN and the loop starts at i = 0, the trick is INT_MIN is the smallest possible int value, so first will compare <= to all values of the array and therefore will not shadow a smaller value. It is also a good default return value for a function that finds the maximum value in an array when passed an empty array.
For your case study, the INT_MIN approach is does not work and the algorithm would fail on an array with a single repeated value: at the end of the scan, first would be set to that value and second would still be INT_MIN.
testing first == second would yield a second largest value equal to INT_MIN, which is incorrect.
testing second == INT_MIN to determine if all values are identical would be incorrect too as an array with values { 1, INT_MIN } would indeed have a second largest value equal to INT_MIN.
Your approach works correctly and the alternative would need to be written differently, with an extra variable. Indeed the solution presented in this article is incorrect, and so is this one, this one, this one and countless more random code across the Internet.
I've added some comments where I saw some problems. Hopefully I caught all the problems. Code below.
#include <stdio.h>
int main(void) {
// int x[10]; I moved this to under where you ask the user for the array size.
int i, n;
// int first=x[0]; This should be written after the user has inputted their numbers. Because what is in x[0]? user hasn't entered anything yet
// int second=x[0]; Same reason as ^
printf("Input the size of array :");
scanf("%d",&n);
int x[n]; // This should be here because you asked the user what the size of the array is.
printf("Input %d elements in the array :\n",n);
for(i=0; i<n; i++)
{
printf("x[%d]: ", i);
scanf("%d", &x[i]);
}
// You should put your first and second int's here
int first=x[0];
int second=x[0];
for (i=0; i<n ; ++i)
{
if (first<x[i])
{
second = first;
first = x[i];
}
else if (x[i] > second && x[i] != first)
{
second = x[i];
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d", second);
return 0;
}
int first=x[0];
int second=x[0];
x isn't initialized yet.
Prints -1 if no second largest element is found.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int findNotSame(long long int a[],long int n)
{
long long int temp = a[0];
int flag = 0;
long int i;
for(i=0;i<n;i++)
{
if(a[i]!=temp)
return 1;
}
return 0;
}
long long int findMax(long long int a[],long int n)
{
long int i;
long long int max = a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max = a[i];
}
return max;
}
int main() {
long int i,j,n;
scanf("%ld",&n);
long long int a[n];
if(n<2) //There cannot be scond largest if there;s only one(or less) element.
{
printf("-1");
return 0;
}
for(i=0;i<n;i++) //Read elements.
scanf("%lld",&a[i]);
if (!findNotSame(a,n)) //Check if all the elements in array are same if so, then -1.
{
printf("-1");
return 0;
}
long long int max = findMax(a,n); //Find maximum element(first).
long long int max2 = -999999999999999; //Initialize another max which will be the second maximum.
for(i=0;i<n;i++) //Find the second max. element.
{
if(a[i]>max2 && a[i] != max)
max2 = a[i];
}
if(max == max2) //Incase if second max(largest) is same as maximum
max2 = -1;
printf("%lld",max2);
return 0;
}
All solution is better, but some fail when the same items available in the array
like,
int arr[] = {56, 41, 19, 33, 13, 23, 25, 56};
56 available in two times,
so for this solution,
int arr[] = {56, 41, 19, 33, 13, 23, 25,56};
var max = arr[0];
var secMax=-1;
var size = arr.length;
for(var l = 1; l < size; l++) {
if (max < arr[l]) {
secMax = max;
max = arr[l];
} else if (secMax < arr[l] && arr[l] != max) {
secMax = arr[l];
}
}
System.out.println("Second largest number :-" + secMax);
import ast
input_str = input()
input_list = ast.literal_eval(input_str)
if len(input_list)<2:
print("not present")
else:
i=input_list[0]
j=i
for index_val in input_list[1:]:
if i<index_val:
j=i
i=index_val
elif index_val>j and index_val!=i:
j=index_val
elif i==j and index_val<j:j=index_val
if i==j:
print("not present")
else:
print(j)
This works,
val arr=Array(4,1,2,4,5,5,7,18,10,5,7)
var firstAndSecondIndex:(Int,Int)=null
for(indexVal <- 2 to (arr.size -1))
firstAndSecondIndex match {
case null =>
println("0,0")
firstAndSecondIndex=(0,1)
case value =>
value match {
case value if arr(indexVal) == arr(value._1) || arr(indexVal) == arr(value._2) =>
println("equals")
case value if arr(indexVal) > arr(value._1) =>
println("1,0")
value match {
case value if arr(indexVal) > arr(value._2) && arr(value._1) > arr(value._2) =>
firstAndSecondIndex=(indexVal,value._1)
case value if arr(indexVal) > arr(value._2) && arr(value._1) < arr(value._2) =>
firstAndSecondIndex=(indexVal,value._2)
case value if arr(indexVal) < arr(value._2) =>
firstAndSecondIndex=(indexVal,value._2)
}
case value if arr(indexVal) < arr(value._1) =>
println("1,1")
value match {
case value if arr(indexVal) > arr(value._2) =>
firstAndSecondIndex=(indexVal,value._1)
case value if arr(indexVal) < arr(value._2) =>
println("not greater")
}
}
}
val secondLargest= arr(firstAndSecondIndex._1) < arr(firstAndSecondIndex._2) match {case true => arr(firstAndSecondIndex._1) case false => arr(firstAndSecondIndex._2)}
int arr[] = {56, 41, 19, 33, 13, 23, 25};
int max = 1;
int secondMax = 0;
for (int i = 0; i < arr.length; i++) {
int getValue = arr[i];
if (max == 1) {
max = getValue;
secondMax = arr[1];
} else {
if (max < getValue) {
secondMax = max;
max = getValue;
} else if (secondMax < getValue) {
secondMax = getValue;
} else {
// Nothing Do
}
}
}
System.out.println("" + secondMax);
Java code to find the largest and second largest number in an array without sorting and using a single loop:
package programs;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int largest = -1;
int secondlargest = -1;
int numberPos = -1;
int numberPos1 = -1;
int[] arr = {22, 33, 9000, 70, 9000, -1, -10, -3, 22, 99, 100, 10000};
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
numberPos = i;
largest = arr[i];
}
}
for (int i = 0; i < arr.length; i++) {
if (secondlargest < arr[i] && secondlargest < largest && arr[i] != largest) {
secondlargest = arr[i];
numberPos1 = i;
}
}
System.out.println("Largest number is "+largest+" with position "+numberPos);
System.out.println("Second largest is "+secondlargest+" with position "+numberPos1);
}
}

c programming regarding arrays and minimum?

Build a program which reads from the user an array with n elements and finds the element with the smallest value.Then the program finds the number of the elements which have an equal value with this minimum.The found element with the smallest value along with the number of the elements which have an equal value with the minimum of the array should be displayed on screen..
I wrote this code :
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int number[n];
printf("Enter the size of array you want");
scanf("%i", &n);
int x;
for (x = 0; x < n; x++) {
int num;
printf("\nEnter a Integer");
scanf("%i", &num);
number[x] = num;
if (number[x] < min)
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min = number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
return 0;
}
But the problem is that when I run this,and I add the integers,it doesnt find the smallest value and how time its repeated correctly!
Where am I wrong?
Assuming your compiler has support for variable length arrays, you need to re-order the calls
int number[n];
scanf("%i", &n);
so that you know the value for n before declaring the array
scanf("%i", &n);
int number[n];
After that, you should initialise min to a larger value to avoid ignoring all positive values
int min = INT_MAX;
(You'll need to include <limits.h> for the definition of INT_MAX)
Finally,
if (min = number[i])
assigns number[i] to min. Use == to test for equality.
Your compiler should have warned you about "assignment in conditional statement" for this last point. If it didn't, make sure you have enabled warnings (-Wall with gcc, /W4 with MSVC)
you are checking array element <0 in line:
if (number[x] < min/*as u specified min =0 before*/),...
so the minimum is set to be zero and there is no replacement actually happening..
The full solution:
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int number[n];
printf("Enter the size of array you want");
scanf("%i", &n);
int x,y;
for (y = 0; y < n; y++)
{
printf("\nEnter a Integer");
scanf("%i", &number[y]);
}
min=number[0];
for (x = 0; x < n; x++) {
if (number[x] < min)
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min == number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
return 0;
}
for (i = 0; i < n; i++) {
if (min = number[i])
count++;
}
Replace min = number[i] with min == number[i].
1.Only After the user input the array size, then you can determine the size of the array number.As the size of the array are uncertain, you should use malloc to allocate the array dynamically.
2.you should set min to the first element of the array. As the min of user input may be great than zero, if you set min to zero, then it will return zero even though the minimum is great than zero
3.you should use == but not = to test the equality of two numbers.
4.last, you should use free to make the memory available and avoid memory leak.
Below is the full program:
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int* number;
printf("Enter the size of array you want");
scanf("%i", &n);
number = (int*)malloc(sizeof(int)*n);
int x;
for (x = 0; x < n; x++) {
int num;
printf("\nEnter a Integer");
scanf("%i", &num);
number[x] = num;
if( x == 0 || number[x] < min )
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min == number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
free(number);
number = NULL;
return 0;
}
In your code
if (min = number[i])
you assigned number[i] to min. You should write
if (min == number[i])
instead.
There are couple of things wrong on your code. First you defined array number[1]. Secondly min in initialised to min = 0.
I suggest defined the array for a maximum possible size, like number[100]. And read the numbe of inputs n from the user, and only use the first n elements of the array. For the second issue, define min as the maximum number represented by int type.

Resources