Saturday 5 March 2022

NPTEL - WEEK 3 ASSIGNMENT 3 QUESTION 01

Question :

Write a C function to find the kth occurrence of an odd integer in a sequence of non-negative integers, and then call your function from main. 

Your function should be according to the following declaration:

int find_odd(int k);

Input
You are given the input in two lines:

The first line contains a positive integer k. 
In the second line, you will be given a sequence of numbers. 

You have to find the kth occurrence of n in the sequence below. 

The second line consists of a sequence of non-negative integers,
terminated with a -1.  The -1 is not part of the sequence.

Output
If there are  k odd numbers in the sequence, then output the  kth
occurrence of odd in the sequence. Otherwise, output  -1.

Solution :

#include<stdio.h>
int find_odd(int k)
{
    int seq, count=0, num;
   
        while(seq != -1)
    {
        scanf("%d", &seq);
        if(seq%2 != 0)
        {
            count++;
            num = seq;
        }
        if(count == k)
        {
            break;
        }
    }
    return num;
}

int main()
{
    int k, seq = 0,num, count=0;

    scanf("%d", &k);

    num = find_odd(k);
   
    printf("%d", num);
    return 0;
}

No comments:

Post a Comment