C Programming – HackerRank Solution | Leaders of an array 1 |

(HackerRank) Write a Modular C Programming code to solve Leaders of an array 1, An element is called a leader if there exists no element greater than it on the RHS.

Given an array, Count leaders of an array. An element is called a leader if there exists no element greater to it on the RHS.

Input Format

First Line contains ‘N’, the number of array elements. The next line contains an ‘N’ array of elements separated by a space

Constraints

N>0 and N<=10^4 0<=a[i]<=10^9

Output Format

Display the count of leaders

Sample Input 0

-4

Sample Output 0

Invalid

Sample Input 1

5
5 4 3 2 1

Sample Output 1

5

Explanation 1

5 is an leader, since there is no element greater to 5 on RHS
4 is an leader, since there is no element greater to 4 on RHS
3 is an leader, since there is no element greater to 3 on RHS
2 is an leader, since there is no element greater to 2 on RHS
1 is an leader, since there is no element greater to 1 on RHS

Number of leaders are 5

Refer: C Programming HackerRank all solutions for Loops | Arrays | strings

 

CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main() {
    int n;
    scanf("%d",&n);
    if(n>0)
    {
        int i,j,array[n],leader=0,status;
        for(i=0;i<n;i++)
        {
            scanf("%d",&array[i]);
        }
        for(i=0;i<n;i++)
        {
            status=1;
            for(j=i+1;j<n;j++)
            {
                if(array[i]<array[j])
                    status=0;
            }
            if(status==1)
                leader++;
        }
        printf("%d",leader);
    }
    else{
        printf("Invalid");
    }
}

OUTPUT

Congratulations, you passed the sample test case.

Click the Submit Code button to run your code against all the test cases.

Input (stdin)

-4
Your Output (stdout)

Invalid
Expected Output

Invalid

 

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University

Leave a Comment