You are on page 1of 13

LOOPs 1.

[10 marks] Write a program that finds all prime numbers between two given integers a and b (a<b). Print the prime numbers and also the number of such primes. Submit the file primes.c and primes.out 2. [5 marks] Write a function that plots the function y = x3 - 5x2 - 5x + 7 between -2 and +5.5 in steps of 0.2. Evaluate the function at each of the points a, a+h, a+2h, ... , b to find the minimum and maximum range of the function in [a, b]. The function will be plotted with y in the horizontal direction, by printing *'s. First find the minimum and the maximum value of the function within this range. Let they be miny and may respectively. To plot y=K, use a line with (K-miny)*50/(maxyminy) blanks followed by one '*'. Submit the files plot.c and plot.out 3. [5 marks] Use the bisection method to find a real root of the above function between 0 and 5. The method of successive bisection works as follows: Start with a lower bound l and an upper bound u such that f(l)*f(u) > 0, ie, f(l) and f(u) are of opposite signs. Then there is a foot of f(x) between l and u. Write a loop where in each iteration, you compute the middlepoint (mid) of the current interval [l, u]. Evaluate f(mid), and based on the sign of f(mid), change the current interval to [l, mid] or to [mid, u]. The loop terminates when width of the interval becomes smaller than 10-10 Submit the files bisection.c and bisection.out
FUNCTIONs Part 1. Fie to submit: primepalin.c An integer is said to be a palindrome if it is equal to its reverse. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N, 1 N 1000000. You must find the smallest integer M N such that M is a prime number and M is a palindrome. For example, if N is 31 then the answer is 101. Input A single integer N, (1 N 1000000) Output Your output must consist of a single integer, the smallest prime palindrome greater than or equal to N.

Part 2. File to submit: rootfind.c, root.out a) Write a fundtion double power (double x, int n) to compute x to the power n. b) double nRootBisection(double y, int n) computes the n-th root of y via bisection method. This function should make calls to the power( ) function defined in 1. A root is to be found with a tolerance of 0.000001. Print the number of iterations required.

Bisection method: Bisection is a numerical algorithm for iteratively converging on a solution of a function f(x) known to lie inside some interval [a,b]. The algorithm evaluates the function f(x) at the midpoint of the interval [a,b], x = (a+b)/2. and then tests to see in which of the subintervals [a,(a+b)/2] or [(a+b)/2,b] the solution lies. This procedure is then repeated with the new interval, as often as needed to locate the solution within the desired accuracy. For the problem of finding the n-th root of y, we want to solve for the value x such n that f(x) = x - y = 0. c) Newton-Raphson algorithm: Another numerical algorithm for converging on a n numerical solution of f(x) = x - y = 0 is the Newton-Raphson method. This algorithm starts with an initial guess for x and then at each iteration updates the estimated x using the equation: x = (x - f(x)) / f'(x), where f'(x) is the first derivative. This process is repeated until the change in x is within the numerical tolerance interval around zero. Write the function
double nRootNewton(double y, int n) to implement this method. Print the root found and the number of iterations required to find a root with a tolerance of 0.000001.

d) Write a main( ) function that tests the above functions to calculate the following:
1. 2. 3. 4. 5.

5 Find the value of 2.317 Find the 4th root of 630 Find the 10th root of 2000 Find the 20th root of 1000000 and a few more examples

***Consider an integer in which each digit is either 0 or 1. Write a program to rearrange the digits such that all the 0s appear before the 1s. Output the resulting number.
sample input: 01001010101 sample output: 00000011111

2.Write the following functions:


A.

int isprime (int n) returns 1 if n is a prime number, 0 otherwise. isprime has to be implemented using a recursive function.

B.

int numconcat (int m, int n) returns the number which is a concatenation of m and n, e.g., numconcat(561, 82) returns the number 56182. C. We will say two primes form a concat-pair if both of their concatenations are also prime. For example, 37 and 67 is a concat-pair since the concatenations 3767 and 6737 are primes. Find all pairs of primes between N1 and N2 (N1 < N2 are taken as input from the user) such that they form a concat-pair.

BONUS QUESTIONS (not to be evaluated as a component of this assignment)


2.

Two frogs are sitting at the bottom of a flight of 10 steps and debating in how many ways then can jump up the stairs. They can jump one, two or three steps at once. For example, they can cover the 10 steps by jumping (3,3,3,1) or (2,3,2,1,2) or other suitable combinations of steps. Their mathematics is not very strong and they approach you for help in order to find out the total number of possibilities they have to reach the top. Note that the order of the steps is important here, i.e., (3,3,3,1) is treated distinct from (1,3,3,3) for example. Write a program that takes input the number of steps of flight to be covered. Output: Number of total ways to reach to the top in the first line followed by all the solutions (one solution in one line). INPUT Number of steps to be covered: 4 OUTPUT Total number of solutions: 7 1111 121 112 211 13 31 22
3.

Write a program that takes input a number, N (number of digits >


A.

3). Write a function that prints N in binary representation.

Write another function that determines the difference between number of 1's and 0's in binary representation of N. Your program intitially take N and then print it's binary representation and the differences in 1's & 0's. Next, remove the rightmost digit of N and print it's binary representation and the differences in 1's & 0's. Repeat this step until only single digit is left. INPUT 1234 OUTPUT 1234 10001101110 1 123 1111011 5 12 1100 0 1 1 1 n Write a program that takes input b and n (n>0,b>0), compute b , i.e., value of b raise to the power n recursively (no loops).
4.

B.

In mathematics, arrays can be used to represent vectors in n-space (e.g., a 3-element array can represent a 3-dimensional vector). Thus a 3-dimensional vector x x i+x j+x k can be represented using an array whose elemnts are: x x x . The 11 2 3 1 2 3 norm of a vector (also known as the Taxicab norm) is the sum of the absolute values of the vector components (||x||=|x |+|x |+|x |). On the other hand, the Euclidean norm 1 2 3 of the vector x is given by the square-root of the sum of the squares of the weight of its components.
A.

Write a function named "oneNorm" that computes the 1norm of a vector having n components. Use any function to compute absolute values of floating-point numbers. The prototype of your function should be double oneNorm(double x[ ], int n)

where x represents the vector and n represents the number of components (i.e., the dimensionality) of the vector. B. Write a function "twoNorm" that computes the Euclidean norm (also known as the 2-norm) of a given vector. C. It is possible to subtract two vectors (of the same dimensionality) by subtracting the corresponding weights of their components separately. Note that this operation yields a vector. The distance between two vectors x and y is defined to be the norm of their difference. Write a function that computes the distance between two given vectors. One of the parameters to the function must specify the type of the norm to be used to compute the distance. Use the functions prepared in parts A and B. The prototype of your function should be as follows: double distance(double x[], double y[], int n, int norm) If norm=1 use 1-norm to calculate the distance, if norm=2 use 2norm to calculate the distance else return the value -1.

BONUS QUESTIONS (not to be evaluated as a component of this assignment)


2.

Use fully recursive technique in the following programs: A. int reverseDigits(int n) that returns the positive integer that you get when you reverse the digits of the argument n. For example, when called with the n=12345, this method would return 54321. B. int subsetSum(int[] a, int n, int goal) that checks if it is possible to select some subset of the first n elements of the array a so that the selected elements add up exactly to goal.

------------------------------------------------------------------------------------------------------In the rail fence cipher, the plaintext is written downwards and diagonally on successive "rails" of an imaginary fence, then moving up when we reach the bottom rail. When we reach the top rail, the message is written downwards again until the whole plaintext is written out. The message is then read off in

rows. For example, if we have 3 "rails" and a message of 'this is a test', the cipherer writes out: t i e h s s t s i a t

The encrypted text then reads as: tie hssts iat Write a C program to do the following: A. Read the number of rails (int no_of_rails) and the message stream in a character array (char sm[]). The characters should be read one by one and filled into the array until EOF. Assume that the maximum number of characters that can be read is 100. B. Display the rail fence using the function void display(char sm[], int no_of_rails). C. Write a function void encrypt(char sm[], char c[], int no_of_rails) which encrypts the meassage in sm[] using rail fence cipher and stores the result in c[]. The cipher text then should be printed from the main function. D. Write a function void decrypt(char c[], char dm[], int no_of_rails) that will decrypt (i.e., given the cipher c[], shall obtain the original message back) and store the original message in dm[] (ignoring the position of the white spaces this time). The decrypted result should be printed from the main function. Your program should ask the user whether he/she wants to (0) Display (1) Encrypt (2) Decrypt or (3 and above) exit from the program. Example execution: Enter number of rails: 3 Enter the plaintext:> this is a test Enter your choice: 0 t i e h s s t s i a t

Enter your choice: 1 Cipher text: tie hssts iat Enter your choice: 2 Decrypted text: thisisatest Enter your choice: 3

2.

Write a C program to implement a function that finds out the longest word in a text stream (terminated by EOF) and returns the length of the string. Both the longest word and the length should be printed from the main function. If there are two or more words that have the same length and qualify to be the longest, print the first one. Sample execution: Enter the text stream:> Indian Institute of Technology, Kharagpur The longest word is: Technology, The length of the longest word is: 11 BONUS QUESTIONS (not to be evaluated as a component of this assignment)
3.

Write a function int LowerToUpper(char *source, char *convert) and int UpperToLower(char *source, char *convert) that converts a given stream of characters (terminated by EOF) from lower case to upper case and vice versa (do not use any standard inbuilt String Functions) and print the converted characters and the number of characters converted from the main function. The program should provide the user with the options (0) LowerToUpper (1) UpperToLower (3 and above) exit. 4. Write a recursive function int charSum(char *s) that returns the number of vowel characters present in the string *s. Print the sum from the main function. ------------------------------------------------------------------------------------------------------Write a C program to read a number N and print out the prime factors of N in non-ascending order. Repeated factors must be printed. For example, if the input is 36, then the output should be 3 3 2 2. Use mergesort to sort the elements.
1.

Write a C program that performs the following. The user inputs a number (say N) and then enters a series of numbers from 1 to N. Your program should determine which number (or numbers) is missing or duplicated in the series, if any. For example, if the user entered N as 5 and then entered the following sequences, the results should be as shown. Input Sequence Output ---------------------- --------------12345 Nothing bad

However, if N were 7, the user would see the results on the right for the following number entries: Input Sequence Output ---------------------- --------------13245 Missing 6 Missing 7 And if N were 10 and the user entered the numbers shown on the left, note the list of missing and duplicate numbers: Input Sequence Output ---------------------- --------------1 2 4 7 4 4 5 10 8 2 6 Duplicate 2 ( 2 times) Missing 3 Duplicate 4 ( 3 times ) Missing 9 The program should check the value of N that the user inputs to ensure that it does not exceed the size of any array you might be using for storage. ------------------------------------------------------------------------------------------------------Write a C program to find out the largest element in the main diagonal and the smallest element in the secondary diagonal of an N X N input matrix.
1.

A quadrilateral in the X-Y plane can be specified by eight real numbers representing the coordinates of its four corners. Define a structure to represent a quadrilateral using eight double variables. A. Implement a header file "quadrilateral.h" that defines a structure named quad representing a quadrilateral. In addition, the header should declare a bunch of function prototypes: quad readQuad() to read the corners of the quadrilateral, int isRectangle(quad q) to test if the quadrilateral is a rectangle, int areaRect(quad q, double *area) to find the area of the quadrilateral if it is a rectangle else send out an appropriate signal indicating that area cannot be computed, int withinRect(quad q, double x, double y) that, in case if q is a rectangle, checks whether the point (x,y) lies within the rectangle. B. Implement the function definitions quad readQuad(), int isRectangle(quad q), int areaRect(quad q, double *area) and int withinRect(quad q, double x, double y) in a seprate file "quadrilateral.c". C. Hence, construct a static library "libquad.a".

D.

Write a separate C program "testquad.c" to (a) read a quadrilateral q1 and (b) check if q1 is a rectangle. If q1 is a rectangle then (c) find its area. Then (d) read another quadrilateral q2 and (e) check whether q2 is fully contained within q1. Use only the functions defined in the library "libquad.a" to implement "testquad.c".

BONUS QUESTIONS (not to be evaluated as a component of this assignment)


2.

3.

Write a C program to A. Create a data structure that stores a person's First Name (string), Mobile Number (6 digit integer) & Age (integer). B. Create an array with the elements representing the above defined data structure (size of array < 20). C. Apply quicksort and sort the array according to the phone numbers. Print the sorted array (print all the details). Write a C program for the following:

Input First line contains two integers R and C, the number of rows and columns in a matrix respectively. Then follow R lines, each containing C space separated integers. Output Print a single integer - a value in the matrix that is smallest in its row but highest in its column. If no such value exists, then print "GUESS" (without quote). Constraints 1 <= R, C <= 100 Example 1 Input: 23 988 2 6 11 Output: 8 Example 2 Input: 33 9 8 11 2 6 34

5 9 11 Output: GUESS Example 3 Input: 22 10 10 10 10 Output: 10 Explanation of Sample Cases Example 1: The first row contains 9, 8, 8. Observe that both 8 are the minimum. Considering the first 8, look at the corresponding column (containing 8 and 6). Here, 8 is the largest element in that column. So it will be chosen. Example 2: There is no value in the matrix that is smallest in its row but largest in its column. Example 3: The required minimum/maximum in matrix is not determined uniquely, but the required output is determined uniquely! Instructions
Keep your bags and other belongings at the back of the lab Name your program as ctest1.c At the very beginning of the program file ctest1.c add the following

comments. Replace "FOOLAN BARIK" by your name, "15CS10001" by your roll number and "52" by your machine number
/******************************************/ /*********ROLL NO: 15CS10001***************/ /*********NAME: FOOLAN BARIK***************/ /*********MACHINE NO: 52 /******************************************/

Consider the following algebraic system: The system of integers modulo p, written Z/p, is a finite algebraic system consisting of the symbols 0, 1, 2, ... p-1. Addition of a and b is defined by the rule "add a and b, then divide by p and take the remainder." Thus, if a=5, b=9 and p=11, then (a+b) modulo p is 5 + 9 3 modulo 11. Multiplication is defined by the rule "multiply a and b, then divide by p and take the remainder." Thus, ifa=2, b=9 and p=11, then (a*b) modulo p is 2 * 9 7 modulo 11. Odd Machines A number a is called a quadratic residue mod p if there is a number b such that b = a modulo p. In other words, quadratic residues are squares modulo p. Assume 0 <= a <= p-1. Also 0 <= b <=p-1. Devise a C program that does the following:
2

1. Reads an integer value p from the input. You can assume that the user knows that the input is prime and you do not need to check in your program whether p is prime. 2. Implements a function
int ifresidue(int a, int p)

that takes as parameters a and p and returns 1 only if a is a square modulo p. Else it returns 0. 3. Iteratively uses the function ifresidue(int a, int p) and prints out a table indicating "YES" where a is a square modulo p else indicating "NO".
Sample test case: Enter the value of p: 11 Output: The table is: 0 YES 1 YES 2 NO 3 YES 4 YES 5 YES 6 NO 7 NO 8 NO 9 YES 10 NO

Even Machines A number b is a multiplicative inverse of a modulo p if ab = 1 modulo p. Assume 1 <= a <= p-1. Also 1 <= b <= p-1. Devise a C program that does the following: 1. Reads an integer value p from the input. You can assume that the user knows that the input is prime and you do not need to check in your program whether p is prime. 2. Implements a function
int inverse(int a, int p)

that takes as parameters a and p and returns the value of b (i.e., the inverse of a). 3. Iteratively uses function inverse(int a, int p) and prints out a table of inverses modulo p.
Sample test case: Enter the value of p: 11 Output: The table is: 1 1 2 6 3 4 4 3 5 9 6 2 7 8 8 7 9 5 10 10

Class Test II

Instructions
1. 2. 3.

Keep your bags and other belongings at the back of the lab Name your program as ctest2.c At the very beginning of the program file ctest2.c add the following comments. Replace "FOOLAN BARIK" by your name, "15CS10001" by your roll number and "52" by your machine number /******************************************/ /*********ROLL NO: 15CS10001***************/ /*********NAME: FOOLAN BARIK***************/ /*********MACHINE NO: 52 /******************************************/ Even Machines Consider the following structure representing the distance in feet and inches:
typedef struct DistanceType{ int feet; float inch; } Distance;

where 0 <= inch < 12 is the only restriction. Write a C program that implements the following functions: (1) Add two distances using: void addDist(Distance d1, Distance d2, Distance *sum) (2) Find the difference of two distances: void differDist(Distance d1, Distance d2, Distance *differ) (3) Using the function differDist compare two distances : int compareDist(Distance d1, Distance d2). If d1=d2 then signal 0, if d1>d2 signal 1 and if d1<d2 signal -1. (4) Given a distance triplet (d1,d2,d3), implement a function int validTriangle(Distance d1, Distance d2, Distance d3) to check whether a triangle can be formed that has d1, d2 and d3 as the lengths of its three sides respectively. Use the function compareDist to implement validTriangle. Now write the main function to read a distance triplet (d1,d2,d3). If the distance triplet forms a valid triangle then first (a) check if the triangle is equilateral, isosceles or scalene and respectively print EQUILATERAL, ISOSCELES or SCALENE on screen and finally (b) calculate the area of the triangle by appropriately using all the above defined functions. To calculate and print the area call a function int areaTriangle(Distance d1, Distance d2, Distance d3, int *sqfeet, float *sqinch) that computes the area (the square feet in the pointer *sqfeet and the square inch in the pointer *sqinch). If the triplet is not a valid triangle you should print COMPUTATIONS CANNOT BE DONE.

Odd Machines Consider the following structure representing span in meters and centimeters:
typedef struct spanType{ int meter; float centimeter; } Span;

where 0 <= centimeter < 100 is the only restriction. Write a C program that implements the following functions: (1) Add two spans using the function: void addSpan(Span s1, Span s2, Span *sum) (2) Find difference of two spans: void differSpan(Span s1, Span s2, Span *differ) (3) Compare the length of two spans using function differSpan: int compareSpan(Span s1, Span s2) which should signal 0 if s1=s2, signal 1 if s1>s2 and signal -1 if s1<s2. (4) Multiply two spans: productSpan(Span s1, Span s2, int *sqm, float *sqcm) (the square meter in the pointer *sqm and the square centimeter in the pointer *sqcm). Now write the main function which would read a span quadruplet s1, s2, s3, s4 and then appropriately use all the above functions to (a) check if it is possible to draw with these four spans a square or a rectangle or only a quadrilateral printing out RECTANGLE, SQUARE or QUADRILATERAL respectively and (b) if it is possible to draw a square or a rectangle then compute the length of the diagonal, perimeter and area. You might use separate functions to calculate each of these quantities, however, always making appropriate use of the above defined functions.

You might also like