Introduction To Programming In C Week 3 Answers

                     

Q1. 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. 

Code:-

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

int main()
{
  int k, seq; 
  scanf("%d",&k); 
  seq=find_odd(k); 
  printf("%d", seq); 
  return 0;
}

Q2. In this question, you have to output the “moving average” of asequence of non-negative numbers. The moving average is the sequenceof averages of the last 2 entries. For the first number, no averageis output.

Code:-

#include<stdio.h> 
int main() 
{
  float a,b; 
  scanf("%f%f", &a, &b);
  do
  {

    printf("%.1f ", (a+b)/2); 
    a=b; 
    scanf("%f", &b);
   }while(b!=-1);
   return 0;
}

Q3. Write a C program to list all the factorial numbers less than or equalto an input number n.

Code:-

#include<stdio.h> 
#include<stdlib.h>
int main()
{
   int n, i=1, j, fact; 
   scanf("%d", &n); 
   while (1) 
   {
     fact = 1; 
     for (j=1; j<=i; j++)
    { 
       fact = fact * j;
    }
     if(fact <= n)
    {
      printf("%d ", fact);
      i++;
    } 
     else
    {
     exit(1);
    }
   }
  return 0;
}