### Introduction To Programming In C Week 5 Answers

Q1. The Collatz function is defined for a positive integer n as follows.
f(n) = 3n+1 if n is odd
n/2     if n is even

Code:-

``````#include<stdio.h>
int main(){
int n;
scanf("%d", &n);
int count = 0;
while(n > 1){
count = count + 1;
if(n % 2 == 0){
n = n / 2;
}
else{
n = n * 3 + 1;
}
}
printf("%d", count);
return 0;
}  ``````

Q2. Consider a matrix M of integers. Divide M into 4 sub-matrices. These sub-matrices are called as Quadrants. Report the Quadrant number which has the smallest minimum-element. If two or more quadrants have same smallest minimum, report the smallest quadrant index.

Code:-

``````#include<stdio.h>
#include<stdlib.h>
int minimum(int matrix , int tx , int ty , int bx ,int by )
{
int min = 32760; // a large positive number
int i , j ;
for ( i = tx ; i <= bx ; i++ )
for ( j = ty ; j <= by ; j++)
if (matrix[i][j] < min)
min = matrix[i][j];
return min;
}
void scan_matrix(int matrix , int rows , int columns) //Scanning the 2D matrix
{
int i,j;
for( i = 0 ; i<rows ; i++)
{
for( j = 0 ; j<columns ; j++)
{
scanf("%d", &matrix[i][j]);
}
}
}
int main(void)
{
int rows , columns;
int matrix; //Define two-dimensional matrix
scanf("%d",&rows);
scanf("%d",&columns);
scan_matrix(matrix , rows , columns); //Function call to scan the
int quad1 = minimum(matrix, 0 , 0 , rows/2 - 1, columns/2 - 1);
int quad2 = minimum(matrix, 0 , columns/2 , rows/2 - 1, columns - 1);
int quad3 = minimum(matrix, rows/2 , 0 , rows - 1 , columns/2 -1 );
int quad4 = minimum(matrix, rows/2 , columns/2 , rows - 1, columns - 1);
int min = 32767; //Largest possible int value
int min_quad_no = 0; //Some initially set value
printf("%d",min_quad_no); //Printing the Quadrant Number with the minimum property result
return 0;
}  ``````

Q3. Write a recursive program that inputs a line of characters from the user. The line may contain blanks. It outputs the line with the characters reversed. The input ends with EOF (end of file).
NOTE: You have to use recursion to solve this, and are NOT allowed to use array to store the input!!

Code:-

``````#include <stdio.h>
void revstr() {
int ch = getchar();
if (ch == EOF) return;
revstr();
putchar(ch);
}
int main() {
revstr();
return 0;
} ``````