The Meaning of An Algorithm:: CCP Lab Manual, 10CPL16/26
The Meaning of An Algorithm:: CCP Lab Manual, 10CPL16/26
Characteristics of an Algorithm:
Input: It may accept a zero or more inputs. Output: It should produce at least one output(result). Definiteness: Each instruction must be clear , well-defined and precise. There should not be any ambiguity. Finiteness: It shoild be a sequence of finite instructions. That is, it should end after a fixed time. It should not enter into an infinite loop. Effectiveness: This means that operations must be simple and are carried out in a finite time at one or more levels of complexity. It should be effective whenever traced manually for the results.
Algorithmic Notations:
Name of the Algorithm Step number Explanatory Comment Termination
Page 1
Symbols used
Meaning associated with symbols Start or end of the flow chart(program) Computational steps (used while assigning and calculating Some results ) Input or output operation Decision making and branching Connector Predefined computation or process (used with functions are used) Repetition or a loop which is normally used to execute a group of instructions for a specifies number of times Flow of control
Page 2
CCP Lab Manual, 10CPL16/26 Flow chart to find the area of rectangle
START
Area=lengrth*breadth
Print area
STOP
Install Turbo C on your machine and follow the steps given below in order to type and run the program given above:
Go to the directory where you have installed Turbo C. Type TC at the DOS command prompt. In the edit window that opens, type the mentioned program above. Save the program as hello.c by pressing F2 or Alt + S. Press Alt + C or Alt + F9 to compile the program. Press Alt + R or Ctrl + F9 to execute the program. Press Alt + F5 to see the output.
Page 3
If you are using a Linux machine, you have to follow the steps mentioned below:
Go to the Linux command prompt (# or $). Type vi filename.c for example vi hello.c The vi editor will open. Press Insert key or I key to start to type. Type the program in the editor. After typing the program, Press Esc, Shift and then : Type w and q followed by filename for example hello.c. w is used to Save a file, where as q to quit. To compile a program, At the command prompt type cc hello.c Type ./a.out to run the program.
Note: It is not possible to execute a parallel program which is written in C language on Turbo
C/Turbo C++ Compiler. Therefore it can be executed on machine with Linux Operating System or by using a tool. To compile a parallel program, at the command prompt type cc -fopenmp filename.c
Structure of a C Program:
Preprocessor Directives Global Declarations (Optional) int main(void) { Local Declarations/Definitions Statements } User Defined Functions (Optional)
Page 4
Lab Program 1
Design, develop and execute a program in C to find and output all the roots of a given quadratic equation, for non-zero coefficients. Algorithm: Roots of a Quadratic equation
Step 1: Start Step 2: Read the values of non-zero coefficients a,b and c. Step 3: Compute the value of discriminant (disc) which is equal to (b*b-4*a*c). Step 4: Check if disc is equal to 0. If true, then go to Step 5. Otherwise, go to Step 6. Step 5: Compute the roots. root1 = (-b)/(2*a) root2=root1 Output the values of roots, root1 and root2. Go to Step 9. Step 6: Check if disc is greater than zero or not. If true, then go to Step 7. Otherwise, go to Step 8. Step 7: Compute the real and distinct roots, root1 = (-b+sqrt(disc))/(2*a) root2 = (-b-sqrt(disc))/(2*a) Output the values of roots, root1 and root2. Go to Step 9. Step 8: Compute the complex and distinct roots. Compute the real part, r_part = (-b)/(2*a) Compute the imaginary part, i_part = sqrt(-disc)/(2*a) Output roots as root1 = r_part + i_part root2 = r_part i_part Step 9: Stop
Page 5
Read a, b, c
disc=b*b-4*a*c
TRUE If disc = 0?
If disc>0?
FALSE
Stop
Page 6
CCP Lab Manual, 10CPL16/26 /* Program to find the roots of a Quadratic equation */
#include<stdio.h> #include<math.h> void main() { float a,b,c,root1,root2,r_part,i_part,disc; clrscr(); printf("Enter the 3 non-zero coefficients\n"); /* Read three non-zero coefficients such as a,b,c */ scanf("%f%f%f",&a,&b,&c); disc=(b*b)-(4*a*c); if(disc==0) { printf("Roots are equal\n"); root1=-b/(2*a); root2=root1; printf("root1=root2=%f",root1); } else if(disc>0) { printf("Roots are real and distinct\n"); root1=(-b+sqrt(disc))/(2*a); root2=(-b-sqrt(disc))/(2*a); printf("root1 = %f \t root2 = %f\n",root1,root2); } else { printf("Roots are complex\n"); r_part=-b/(2*a); i_part=(sqrt(-disc))/(2*a); printf("root1 = %f+i%f \t root2 = %f-i%f\n",r_part,i_part,r_part,i_part); } getch(); }
Output:
First Run: Enter the 3 non-zero coefficients 1 2 1 Roots are equal root1=root2=-1.000000
Page 7
Second Run: Enter the 3 non-zero coefficient 2 5 2 Roots are real and distinct root1 = -0.500000 root2 = -2.000000 Third Run: Enter the 3 non-zero coefficient 2 2 2 Roots are complex root1 = -0.500000+i0.866025 root2 = -0.500000-i0.866025
Page 8
Lab Program 2
Design, develop and execute a program in C to implement Euclids algorithm to find the GCD and LCM of two integers and to output the results along with the given integers. Euclids Algorithm
The method of finding the GCD of two numbers was named after mathematician Euclid form Alexandria and this is often called Euclids algorithm to find GCD of two numbers.
Algorithm: To find GCD and LCM of two non-zero integers using Euclids algorithm and output results along with given integers.
Step 1: Start Step 2: Read the two non-zero integers num1 and num2. Step 3: Keep num1 and num2 in temporary variables to print later. n1 = num1 n2 = num2 Step 4:Compute remainder = num1 % num2. Step 5: Check if remainder is not equal to zero. If true, repeat Step 6 to Step 8. Otherwise (i.e if remainder is equal to zero) goto Step 9. Step 6: Assign num2 to num1. num1=num2 Step 7: Assign remainder to num2. num2= remainder Step 8: Compute remainder = num1 % num2. Goto Step 5. Step 9: Output num2 as GCD of n1 and n2. Step 10: Output (n1*n2) / num2 as LCM of n1 and n2. Step 11: Stop.
Page 9
n1 = num1 n2 = num2
FALSE
while (rem!=0)
Output num2 as GCD of n1 & n2
TRUE
num1 = num2
num2 = rem
Page 10
Page 11
Lab Program 3
Design, develop and execute a program in C to reverse a given four digit integer number and check whether it is a palindrome or not. Output the given number with suitable message. Algorithm: To reverse a four digit number and check whether it is a palindrome or not.
Step 1: Start Step 2: Read the four digit number, digit_no. Step 3: Keep digit_no in a temporary variable to verify with its reverse later and decide whether it is a palindrome or not. num = digit_no Step 4: Initialize reverse to zero. Step 5: Output the four digit number, digit_no. Step 6: Check if digit_no is not equal to zero. If true, repeat Step 7 to Step 9. Otherwise (i.e if digit_no is equal to zero), goto Step 10. Step 7: Compute remainder = digit_no % 10. Step 8: Compute reverse = reverse * 10 + remainder. Step 9: Compute digit_no = digit_no / 10. Goto Step 6. Step 10: Output reverse. Step 11: Check if reverse is equal to num. If true, output the message The number is a palindrome. Otherwise, output the message The number is not a palindrome. Step 12: Stop.
Page 12
num = digit_no
rev =0
FALSE
while (digit_no!=0)
TRUE
digit_no = digit_no / 10
FALSE
STOP
Page 13
CCP Lab Manual, 10CPL16/26 /* C Program to find whether a given 4-digit integer is palindrome or not */
#include<stdio.h> void main() { int digit_no,num,rev,rem; clrscr(); printf("Enter the four digit integer number\n"); scanf("%d",&digit_no); num=digit_no; rev=0; printf("The given integer number = %d\n",num); while(digit_no != 0) { rem=digit_no%10; rev=rev*10+rem; digit_no = digit_no/10; } printf("The reverse of given number %d is %d\n",num,rev); if(num == rev) printf("The given number %d is a palindrome\n",num); else printf("The given number %d is not a palindrome\n",num); getch(); }
Output: First Run: Enter the four digit integer number 2442 The given integer number = 2442 The reverse of given number 2442 is 2442 The given number 2442 is a palindrome Second Run: Enter the four digit integer number 1234 The given integer number = 1234 The reverse of given number 1234 is 4321 The given number 1234 is not a palindrome
Page 14
Lab Program 4
Design, develop and execute a program in C to evaluate the given polynomial f(x) = a4x4 + a3x3 + a2x2 + a1x + a0 for given value of x and the coefficients using Horners method. Method: Evaluating the polynomial means, finding the value of f(x), given the value of x and the
co-efficients, a0,a1,a2,,an In general, the polynomial can be of the form: (a0+x(a1+x(a2+x(a3++x(an-1+x.an))))) In nested parenthesis expression, innermost parenthesis is evaluated first. So, sum (i.e f(x)) is initialized to a[n]*x. Then, from (n-1)th term to 1st term, sum is repeated calculated by the expression sum = (sum+a[i])*x. At last, 0th term is added to sum.
Page 15
for (i=0;i<=n;i++)
TRUE
Read a[i]
Read x
sum = a[n]*x
FALSE
for (i=n-1;i>0;i--)
TRUE
sum=(sum+a[i])*x
sum=sum+a[0]
Print sum
STOP
Page 16
CCP Lab Manual, 10CPL16/26 /* C program to evaluate a polynomial using Horners method */
#include<stdio.h> void main() { int n,i; float a[20],x,sum; clrscr(); printf("Enter the order of the polynomial\n"); scanf("%d",&n); printf("Enter the (n+1) co-efficients\n"); for(i=0;i<=n;i++) scanf("%f",&a[i]); printf("Enter the value of x\n"); scanf("%f",&x); /*Evaluate the polynomial*/ sum=a[n]*x; for(i=n-1;i>0;i--) sum=(sum+a[i])*x; sum=sum+a[0]; printf("Evaluation of polynomial,f(%f)=%f\n",x,sum); getch(); }
Output: Enter the order of the polynomial 4 Enter the (n+1) co-efficients 1 2 3 4 5 Enter the value of x 2 Evaluation of polynomial, f(2)=129.000000
Page 17
Lab Program 5
Design, develop and execute a program in C to copy its input to its output, replacing each string of one or more blanks by a single blank.
Algorithm: To copy string input to its output, replacing each string of one or more blanks by a
single blank. Step 1: Start Step 2: Read source string. Step 3: Initialize first index of source string to Zero Step 4: Initialize first index of destination string to Zero. Step 5: Check if source string character is equal to null character. If true repeat Step 6 to Step 10. Otherwise goto Step11. Step 6: Copy a character from source to destination. Step 7: Update source and destination index. Step 8: Check if previous stored character is blank. If true goto Step 9. Otherwise goto Step 5. Step 9: Check if current source character is blank. If true repeat Step 10. Otherwise goto Step 5. Step 10: Skip remaining blank spaces from the source string by incrementing the source index by one. Step 11: Terminate the destination string with null character. Stop 12: Print the destination string. Stop 13: Stop.
Page 18
while(src[i]!=\0)
TRUE
FALSE
dest[j]=src[i]
i++
j++
FALS E
if(src[i-1]== )?
TRUE
FALS E
while(src[i]== )?
TRUE
dest[j]=\0 '
i++
STOP
Page 19
CCP Lab Manual, 10CPL16/26 /* C program to copy its input to its output, replacing each string of one or more blanks by a single blank */
#include<stdio.h> void main() { char src[100],dest[100]; int i,j; clrscr(); printf("Enter a string with blanks\n"); gets(src); i=0; /* First index of source string */ j=0; /* First index of destination string */ while(src[i]!='\0') { dest[j]=src[i]; /* Copy a character from source to destination */ i++; /* Update source index */ j++; /* Update destination index */ if(src[i-1]==' ') /* If previous stored character is blank */ { while(src[i]==' ') /* Skip remaining blanks in the source */ i++; } } dest[j]='\0'; /* Terminate the destination string with null character */ printf("The string with single blank : %s", dest); getch(); }
Output:
First Run: Enter a string with blanks CMRIT IN AECSLAYOUT The string with single blank: CMRIT IN AECSLAYOUT Second Run: Enter a string with blanks CMR INSTITUTE OF TECHNOLOGY BANGALORE The string with single blank: CMR INSTITUTE OF TECHNOLOGY BANGALORE
Page 20
Lab Program 6
Design, develop and execute a program in C to input N integer numbers in ascending order into a single dimension array, and then to perform a binary search for a given key integer number and report success or failure in the form of a suitable message. Algorithm: To conduct a binary search for key integer number in an ascending ordered array of
numbers. Step 1: Start Step 2: Read the number of elements in an array (i.e.. n). Step 3: Initialize index i to zero. Step 4: Check if i is less than n (total number of elements in the array). If true, then goto Step 5. Otherwise, goto Step 6. Step 5: Read the ith item in the array, a[i]. Increment i and goto Step 4. Step 6: Read the key element to be searched in the array. Step 7: Initialize low to 0 and high to (n-1). Step 8: Check if low is less than or equal to high. Execute Step 9 to Step 11 until this satisfied. When condition fails, Output the message Key Not found.... search and goto Step 12. Step 9: Calculate mid which is (low+high)/2. Step 10: Check if key is equal to a[mid]. If true, Output the message Key found....Successful search and goto to Step 12. Otherwise, goto Step 11. Step 11: Check if key is less then a[mid]. If true, the key is present in the first half of the array. So, update high to (mid-1). Otherwise, the key is present in the second half. So, low is updated to (mid+1). Goto Step 8. Step 12: Stop condition is
UnSuccessful
Page 21
START
Read n
for i=0;i<n;i++
TRUE
FALSE
Read a[i]
Read key
low=0 high=n-1
FALSE
while(low<=high)
TRUE
mid=(low+high)/2
Is key==a[mid] ? ?
FALSE
TRUE
STOP
Is key<a[mid] ?
FALSE
TRUE
high=mid-1
low=mid+1
Page 22
CCP Lab Manual, 10CPL16/26 /* C program to search a key element in ascending order array using binary search technique */
#include<stdio.h> void main() { int a[10],key,n,i,low,mid,high; clrscr(); printf("Enter the number of elements in the list\n"); scanf("%d",&n); printf("Enter the real numbers in ascending order\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("Enter the key element to be searched\n"); scanf("%d",&key); low=0; high=n-1; while(low<=high) { mid=(low+high)/2; if(key == a[mid]) { printf("Key element found. Successful Search \n"); getch(); exit(0); } else if(key<a[mid]) high = mid-1; else low=mid+1; } printf("Key element not found. Unsuccessful Search\n"); getch(); }
Output:
First Run: Enter the number of elements in the list 7 Enter the real numbers in ascending order 3
Page 23
Page 24
Lab Program 7
Design, develop and execute a program in C to input N integer numbers into a single dimension array, sort them in to ascending order using bubble sort technique, and then to print both the given array and the sorted array with suitable headings. Algorithm: To sort the array of integers in ascending order using bubble sort technique.
Step 1: Start Step 2: Read the number of elements into an array (i.e.. n). Step 3: Initialize index i to zero. Step 4: Check if i is less than n (total number of elements in the array). If true, then goto Step5. Otherwise, goto Step 6. Step 5: Read the ith item in the array, a[i]. Increment i and goto Step 4. Step 6: Output the unsorted array elements. Step 7: Initialize index i to zero. Step 8: Check if i is less than n (total number of elements in the array). If true, then goto Step9. Otherwise, goto Step 10. Step 9: Output the ith item in the array, a[i]. Increment i and goto Step 8. Step 10: Initialize pass to 1. Step 11: Check if pass is less than n. If true, goto Step 12. Otherwise, goto Step 15. Step 12: Initialize index i to zero. Step 13: Check if i is less than (n-pass) (i.e there are(n-pass) comparisons to be done in each pass). If true, goto Step 14. Otherwise, increment pass and goto Step 11. Step 14: Check if a[i] is greater than a[i+1] (i.e 2 adjacent elements are compared). If true, then swap the two elements using temporary variable. Otherwise, goto Step 13. Step 15: Output the sorted array elements.. Step 16: Initialize index i to zero. Step 17: Check if i is less than n (total number of elements in the array). If true, then goto Step 18. Otherwise, goto Step 19. Step 18: Output the ith item in the array, a[i]. Increment i and goto Step 17. Step 19: Stop
Page 25
START
Read n
for i=0;i<n;i++
TRUE
FALSE
Read a[i]
for i=0;i<n;i++
TRUE
FALSE
Output a[i]
FALSE
for pass=1;pass<n;pass++
TRUE
for i=0;i<n-pass;i++
TRUE
FALSE
FALSE
if a[i]>a[i+1] ? ?
TRUE
for i=0;i<n;i++
TRUE
FALSE
Output a[i]
STOP
Page 27
Output:
Enter the size of an array 7 Enter the array elements to be sorted: 65 48 36 72 5 7 14 Unsorted array elements are: a[0] = 65 a[1] = 48 a[2] = 36 a[3] = 72 a[4] = 5 a[5] = 7 a[6] = 14 Sorted array elements are: a[0] = 5 a[1] = 7 a[2] = 14 a[3] = 36 a[4] = 48 a[5] = 65 a[6] = 72
Page 28
Lab Program 8
Design, develop and execute a program in C to compute and print the word length of the host machine. Algorithm: To compute and print the word length on the host machine.
Step 1: Start Step 2: Declare two variables to hold word length and minimum or maximum number. Step 3: Initialize word length to Zero. Step 4: Initialize maximum number to 1s complement of Zero. Step 5: Check if maximum number is not equal to Zero. If true repeat Step 6 and Step 7. Otherwise goto Step 8. Step 6: Shift the bits towards left by 1. Step 7: Update the word length. Step 8: Print word length of machine. Stop 9: Stop.
Flowchart:
Start
count=0
n=~0
FALSE
while(n!=0)
TRUE n=n<<1
Stop
count++
Page 29
CCP Lab Manual, 10CPL16/26 /* C Program to compute and print the word length on the host machine */
#include<stdio.h> void main() { int count; /* To hold word length */ unsigned int n; /* To Hold minimum or maximum number */ clrscr(); count=0; /* Initial word length */ n=~0; /* Maximum number: 1's complement of 0 */ while(n!=0) /* As long as value is not Zero */ { n=n<<1; /* Shift the bits towards left */ count++; /* Update the word length */ } printf("Wordlength of Machine=%d-bits\n",count); getch(); }
Output:
If the program is executed on Windows Platform then the output is Wordlength of Machine=16-bits (For 32-bit Machine) If the program is executed on Linux Platform then the output is Wordlength of Machine=32-bits (For 32-bit Machine)
Page 30
Lab Program 9
Design, develop and execute a program in C to calculate the approximate value of exp(0.5) using the Taylor Series expansion for the exponential function. Use the terms in the expansion until the last term is less than the machine epsilon defined FLT_EPSILON in the header file <float.h>. Also print the value returned by the Mathematical function exp( ). The Taylor Series Equation is
Algorithm: To calculate the approximate value of exp(0.5) using the Taylor Series expansion for the
exponential function . Step 1: Start Step 2: Initialize x to 0.5 Step 3: Initialize sum to One. Step 4: Find sum of Exponential Series by repeating the Step 5 to Step7. Step 5: Find term by using the following equation term=pow(x,i)/fact(i) Step 6:Check if term is less than FLT_EPSILON. If it is true goto Step 8 .Otherwise goto Step 7. (FLT_EPSILON is a library constant, the definition is available in float.h header file). The value of this is 1.16219E-07) Step 7: sum=sum+term. Goto Step 5. Step 8: Print the output by using Taylor Series. Stop 9: Print the output by using Mathematical Library Function. Stop 10: Stop.
Page 31
x=0.5
term=pow(x,i) /
fact(i)
TRUE
Is (term<FLT_EPSILON) ?
prod=1 FALSE
for(i=1;i<=n;i++)
TRUE TRUE prod=prod*i
RETURN
Page 32
CCP Lab Manual, 10CPL16/26 /* C Program to calculate the approximate value of exp(0.5) using the Taylor Series expansion for the exponential function */
#include<stdio.h> #include<math.h> #include<float.h> int fact(int); /* A function used to determine the factorial of a number */ void main() { int i; float x=0.5; double sum,term; clrscr(); sum=1; /* Find sum of Exp series */ for(i=1;;i++) { term=pow(x,i)/fact(i); if(term<FLT_EPSILON) break; sum=sum+term; } printf("Using Taylor Series\n"); printf("e^%3.1f=%lf\n",x,sum); printf("Using Library function\n"); printf("e^%3.1f=%lf\n",x,exp(x)); getch(); }
Output:
Using Taylor Series e^0.5=1.648721 Using Library function e^0.5=1.648721
Page 33
Lab Program 10
Design, develop and execute a program in C to read two matrices A (M x N) and B (P x Q) and compute the product of A and B if the matrices are compatible for multiplication. The program must print the input matrices and 3 3 the resultant matrix with suitable headings and format if the matrices are compatible for multiplication, otherwise the program must print a suitable message. (For the purpose of demonstration, the array sizes M, N, P, and Q can all be less than or equal to 3)
Page 34
TRUE
If (n!=p) ?
FALSE
for (row=0;row<m;row++)
TRUE FALSE TRUE
for (col=0;col<n;col++)
TRUE Read a[row][col]
for (row=0;row<p;row++)
TRUE
FALSE TRUE
for (col=0;col<q;col++)
FALSE TRUE TRUE Read b[row][col]
Page 35
B
FALSE TRUE
for (row=0;row<m;row++)
TRUE FALSE TRUE
for (col=0;col<n;col++)
TRUE Output a[row][col]
for (row=0;row<p;row++)
TRUE FALSE TRUE
FALSE TRUE
for (col=0;col<q;col++)
TRUE Output b[row][col]
FALSE
for (row=0;row<m;row++)
TRUE
Output Matrix C
STOP
for (col=0;col<q;col++)
FALSE TRUE
c[row][col]=0
FALSE
for (k=0;k<n;k++)
TRUE
Page 36
Page 37
Page 38
Second Run:
Enter the size of matrix A 23 Enter the size of matrix B 23 Matrix Multiplication is not possible
Page 39
Lab Program 11
Design, develop and execute a parallel program in C to add, elementwise, two onedimensional arrays A and B of N integer elements and store the result in another onedimensional array C of N integer elements. Note: It is not possible to execute a parallel program which is written in C language on Turbo
C/Turbo C++ Compiler. Therefore it can be executed on machine with Linux Operating System or by using a tool.
If you are using a Linux Platform, you have to follow the steps mentioned below: Go to the Linux command prompt (# or $). Type vi filename.c for example vi program11.c The vi editor will open. Press Insert key or I key to start to type. Type the program in the editor. After typing the program, Press Type w and q Esc, Shift and then : followed by file name for example hello.c. w is used for Saving
a file where as q for quit. To compile a program, At the command prompt type cc fopenmp hello.c . Type ./a.out to run the program.
Page 40
Read n
FALSE
for i=0;i<n;i++
TRUE
Read a[i]
FALSE
for i=0;i<n;i++
TRUE
Read b[i]
FALSE
for i=0;i<n;i++
TRUE
Output a[i]
FALSE
for i=0;i<n;i++
TRUE
Output b[i]
Page 41
for i=0;i<n;i++
TRUE
FALSE
c[i]=a[i]+b[i]
FALSE
for i=0;i<n;i++
TRUE
Output c[i]
STOP
/* Parallel Program in C to add, elementwise, two one-dimensional arrays A and B of N integer elements */
#include<stdio.h> #include<omp.h> int main() { int a[10],b[10],c[10],i, n; printf("Enter the number of elements: "); scanf("%d",&n); printf("Enter the elements of 1st array: "); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the elements of 2nd array: "); for(i=0;i<n;i++) scanf("%d",&b[i]);
Page 42
Output:
Enter the number of elements: 4 Enter the elements of 1st array: Enter the elements of 2nd array: The contents of 1st array: a[0]=1 a[1]=2 a[2]=3 a[3]=4 The contents of 2nd array: b[0]=1 b[1]=2 b[2]=3 b[3]=4 c[0]=2,Thread id=0 c[2]=6,Thread id=1 The new array is : c[0]=2 c[1]=4 c[2]=6 c[3]=8 1 1 2 2 3 3 4 4
Page 43
Lab Program 12
Design and develop a function rightrot (x, n) in C that returns the value of the integer x rotated to the right by n bit positions as an unsigned integer. Invoke the function from the main with different values for x and n and print the results with suitable headings. Algorithm for main() function:
Step 1: Start Step 2: Read an unsigned integer that should be less than or equal to 65535. Step 3: Read the value of x i.e. how many times to rotate. Step 4: Find the result by calling rightrot(x,n) function Step 5: Print the output Step 6: Stop.
Page 44
Read x
Read n
result=rightrot(x,n)
STOP
for(i=1;i<=n;i++)
TRUE FALSE Is (x%2==0) TRUE TRUE x=x>>1
FALSE
x=x>>1 x+=32768
RETURN (x)
Page 45
CCP Lab Manual, 10CPL16/26 /* C Program that displays the value of the integer x rotated to the right by n bit positions as an unsigned integer */
#include<stdio.h> unsigned int rightrot(unsigned int, int); void main() { unsigned int x, result; int n; clrscr(); printf("Enter an unsigned integer <=65535\n"); scanf("%u",&x); printf("Rotate %u how many times:",x); scanf("%d",&n); result=rightrot(x,n); printf("rightrot(%u,%d)=%u\n",x,n,result); } unsigned int rightrot(unsigned int x, int n) { int i; for(i=1;i<=n;i++) { if(x%2==0) x=x>>1; else { x=x>>1; x+=32768; } } return x; }
Second Run:
Enter an unsigned integer <=65535
Page 46
Third Run:
Enter an unsigned integer <=65535 32768 Rotate 32768 how many times: 15 rightrot(32768,15)=1
Page 47
Lab Program 13
Design and develop a function isprime (x) that accepts an integer argument and returns 1 if the argument is prime and 0 otherwise. The function is to use plain division checking approach to determine if a given number is prime. Invoke this function from the main with different values obtained from the user and print appropriate messages. Algorithm for main() function:
Step 1: Start Step 2: Read the number n. Step 3: Check if n is equal to zero. If true, then output the message Number is not a prime and goto Step 8. Otherwise, goto Step 4. Step 4: Call the isprime(n) function. Step 5: Check the returned value is equal to Zero. If it is true then output the message Number is not a prime and goto Step 7. Otherwise, goto Step 6. Step 6: Output the message Number is prime. Step 7: Stop.
Page 48
Is (n=0)? FALSE
TRUE
flag=isprime(n)
TRUE
STOP
int prime(int n)
for(i=2;i<=n/2;i++)
TRUE FALSE Is (x%i==0)? TRUE RETURN 0
FALSE
RETURN 1
Page 49
CCP Lab Manual, 10CPL16/26 /* C program to find whether a given number is prime or not by using function */
#include<stdio.h> int isprime(int); void main() { int n,i,flag; clrscr(); printf("Enter an integer number \n"); scanf("%d",&n); if(n == 0) { printf("%d is not a prime number\n",n); getch(); exit(0); } flag=isprime(n); if(flag==0) printf("%d is not a prime number\n",n); else printf("%d is a prime number\n",n); getch(); } int isprime(int x) { int i; for(i=2;i<=x/2;i++) if(x%i == 0) return 0; return 1; }
Second Run:
Enter an integer number 15 15 is not a prime number
Page 50
Lab Program 14
Design, develop and execute a parallel program in C to determine and print the prime numbers which are less than 100 making use of algorithm of the Sieve of Eratosthenes. Algorithm: To find Prime Numbers Using The Sieve Of Eratosthenes.
Step 1: Start Step 2: #pragma omp parallel for Step 3: Check if i is less than or equal to 99. If true, then goto Step 4. Otherwise goto Step 6. Step 4: num[i]=i+1 Step 5: Print Thread id by invoking Library function omp_get_thread_num().Increment i and goto Step 3. Step 6: #pragma omp parallel for Step 7: Check if i is less than or equal to 99. If true, then goto Step 8. Otherwise goto Step 14. Step 8: Check if num[i] is not equal to zero. If true, then goto Step 9. Otherwise increment i and goto Step 7. Step 9: #pragma omp parallel for Step 10: Check if j is less than or equal to 99. If true, then goto Step 11. Otherwise increment i and goto Step 7. Step 11: Check if num[j] is not equal to zero. If true, then goto Step 12. Otherwise increment j and goto Step 10. Step 12: Check if num[j] is a multiple of num[i]. If true, then set num[j]=0. Otherwise increment j and goto Step 10. Step 13: Check if i is less than or equal to 99. If true, then goto Step 14. Otherwise goto Step 15. Step 14: Check if num[i] is not equal to zero. If true, then print Prime numbers which are less than 100. Otherwise goto Step 15. Step 15: Stop.
Page 51
START
FALSE
for (i=0;i<=99;i++)
TRUE
num[i]=i+1
FALSE
if(num[i]!=0)
Z
TRUE
FALSE
for (j=i+1;j<=99;j++)
TRUE FALSE
if(num[j]!=0)
TRUE FALSE
if(num[j]!%num[i]=0)
TRUE
num[j]=0
Page 52
for (i=0;i<=99;i++)
TRUE FALSE
FALSE
if(num[i]!=0)
TRUE
STOP
Output num[i]
Page 53
printf(The prime numbers are: \n); for(i=0;i<=99;i++) { if(num[i]!=0) /*Print all prime numbers (less than 100)*/ printf("%d\t",num[i]); } printf(\n); return 0; }
Output:
num[0]=1,Thread id=0 num[1]=2,Thread id=0 num[2]=3,Thread id=0 num[3]=4,Thread id=0 num[4]=5,Thread id=0 num[5]=6,Thread id=0 num[6]=7,Thread id=0 num[7]=8,Thread id=0 num[8]=9,Thread id=0 num[9]=10,Thread id=0 num[10]=11,Thread id=0 num[12]=13,Thread id=0 num[15]=16,Thread id=0 num[18]=19,Thread id=0 num[21]=22,Thread id=0 num[24]=25,Thread id=0 num[27]=28,Thread id=0 num[30]=31,Thread id=0 num[33]=34,Thread id=0 num[36]=37,Thread id=0 num[39]=40,Thread id=0 num[42]=43,Thread id=0 num[45]=46,Thread id=0 num[11]=12,Thread id=0 num[14]=15,Thread id=0 num[17]=18,Thread id=0 num[20]=21,Thread id=0 num[23]=24,Thread id=0 num[26]=27,Thread id=0 num[29]=30,Thread id=0 num[32]=33,Thread id=0 num[35]=36,Thread id=0 num[38]=39,Thread id=0 num[41]=42,Thread id=0 num[44]=45,Thread id=0 num[47]=48,Thread id=0
num[13]=14,Thread id=0 num[16]=17,Thread id=0 num[19]=20,Thread id=0 num[22]=23,Thread id=0 num[25]=26,Thread id=0 num[28]=29,Thread id=0 num[31]=32,Thread id=0 num[34]=35,Thread id=0 num[37]=38,Thread id=0 num[40]=41,Thread id=0 num[43]=44,Thread id=0 num[46]=47,Thread id=0
Page 54
Page 55
Lab Program 15
Design and develop a function reverses (s) in C to reverse the string s in place. Invoke this function from the main for different strings and print the original and reversed strings. Algorithm for main() function:
Step 1: Start Step 2: Read the string. Step 3: Call the reverse(s) function. Step 4: Stop.
Flowchart:
Start
reverse(char src[])
Read the string n=strlen(src)
reverse(s)
for(i=0;i<n;i++)
STOP TRUE
FALSE
reverse[n]=\0
reverse[n-1-i]=src[i]
Page 56
RETURN
CCP Lab Manual, 10CPL16/26 /* C Program to reverse the given string by using user defined function */
#include<stdio.h> #include<string.h> void reverse(char []); void main() { char s[20]; printf("Enter the string: "); gets(s); reverse(s); getch(); } void reverse(char src[]) { char t; int j, i, n; n=strlen(src); for(i=0, j=n-1;i<j ; i++, j--) { t = src[i]; src[i] = src[j]; src[j] = t; } printf("The Reverse String is : %s",src); }
Output:
First Run: Enter the String ZIA The Reverse String is : AIZ Second Run: Enter the String ACHARYA The Reverse String is : AYRAHCA
Page 57
Lab Program 16
Design and develop a function matchany(s1,s2) which returns the first location in the string s1 where any character from the string s2 occurs, or 1 if s1 contains no character from s2. Do not use the standard library function which does a similar job! Invoke the function matchany (s1. s2) from the main for different strings and print both the strings and the return value from the function matchany(s1,s2). Algorithm for main() function:
Step 1: Start Step 2: Read the First String. Step 3: Read the Second String. Step 4: Call the matchany() function and the value returned is stored in position variable. Step 5: Print Both i.e. First and Second Strings. Step 6: Check if position is equal to -1. If true, then output the message No character of second String is found in the first String. Otherwise output the message Position=. Step 7: Stop.
Page 58
Position=matchany(s1,s2)
is (Position = -1)?
TRUE
FALSE
Output the Position
STOP
for(i=0;s1[i]!='\0';i++)
TRUE
RETURN (-1)
symbol=s1[i]
FALSE
for(j=0;s2[j]!='\0';j++)
TRUE
is (symbol=s2[j])?
FALSE
Page 59
CCP Lab Manual, 10CPL16/26 /* C Program to print the position of the first character of the second string from the first string */
#include<stdio.h> int matchany(char [],char[]); void main() { char s1[20],s2[20]; int position; clrscr(); printf("Enter the first String: "); gets(s1); printf("Enter the second String: "); gets(s2); position=matchany(s1,s2); printf(The First String is : %s\n,s1); printf(The Second String is : %s\n,s2); if(position==-1) printf("No character of %s is present in %s\n",s2,s1); else printf("Postion=%d\n",position); getch(); } int matchany(char s1[],char s2[]) { int i,j; char symbol; for(i=0;s1[i]!='\0';i++) { symbol=s1[i]; for(j=0;s2[j]!='\0';j++) { if(symbol==s2[j]) return (i+1); } } return -1; }
Page 60
Second Run:
Enter the first String SUDHA Enter the second String Z The First String is : SUDHA The Second String is : Z No character of Z is present in SUDHA
Third Run:
Enter the first String MANJUNATH Enter the second String A The First String is : MANJUNATH The Second String is : a No character of a is present in MANJUNATH
Page 61
ADDITIONAL PROGRAMS
Additional Program 1. Write a C program to exchange the values of two variables using a dummy varibale and without using a dummy variable.
void main() { int a,b,dummy; clrscr(); printf("Enter the values of a and b:\n"); scanf("%d%d%d", &a,&b); printf(a=%d and b=%d\n,a,b); printf(Using a dummy variable\n); dummy=a; a=b; b=dummy; printf(a=%d and b=%d\n,a,b); printf(Without using a dummy variable\n); a=a+b; b=a-b; a=a-b; printf(a=%d and b=%d\n,a,b); getch(); }
Additional Program 2. Write a C program to accept the temperature in Fahrenheit and convert it into Celsius.
#include<stdio.h> void main() { float ct,ft; printf(Enter the temperature in Fahrenheit\n);
scanf(%f,&ft);
ct=(ft-32.0)/1.8; printf(Fahrenheit temperature = 6.2%f\n, ft); printf(Celsius temperature = 6.2%f\n, ct); getch(); }
Page 62
CCP Lab Manual, 10CPL16/26 Additional Program 3. Write a C program to find largest of three numbers using if else construct.
void main() { int a,b,c,big; clrscr(); printf(" **** Welcome. This program find Biggest of Three Numbers ****\n"); printf("Enter the value of a , b and c:\n"); scanf("%d%d%d", &a,&b,&c); big=a; if(big<b) big=b; else big=c; printf(" The Biggest Number is : %d",big); getch(); }
Additional Program 4. Write a C program to print the number 5, five times; number 4, four times; number 3, three times; and so on number 1 , once.
#include<stdio.h> void main() { int i,j,num=5; printf(Number pattern\n); for(i=num;i>=1;i--) { for(j=1;j<=i;j++) printf(%d,num); printf(\n); num--; } getch(); }
Output:
Number Pattern 55555 4444 333 22 1
Page 63
Additional Program 6. Write a C program to read a binary number and convert it into decimal number.
#include<stdio.h> void main() { int num,result,digit,sum=0,base=1; printf(Enter Binary Number\n); scanf(%d,&num); while(num!=0) { digit=num%10; num=num/10; sum=sum+digit*base; base=base*2; } printf(Binary : %d\n Decimal : %d\n,num,sum); printf(\n); getch(); }
Page 64
CCP Lab Manual, 10CPL16/26 Additional Program 7. Write a C program to read a decimal number and convert it into binary number.
#include<stdio.h> void main() { int num,result,digit,sum=0,base=1; printf(Enter Decimal Number\n); scanf(%d,&num); while(num!=0) { digit=num%2; num=num/2; sum=sum+digit*base; base=base*10; } printf(Decimal : %d\n Binary : %d\n,num,sum); printf(\n); getch(); }
Additional Program 8. Write a C program to find factorial of a given number using recursion technique.
#include<stdio.h> int fact(int n); void main() { int n,result; printf(Enter the value of n\n); scanf(%d,&n); result=fact(n); printf(%d!=%d\n, n,result); getch(); } int fact(int n) { if(n==0) return 1; return(n*fact(n-1)); }
Page 65
CCP Lab Manual, 10CPL16/26 Additional Program 9. Write a C program to print sum of all integers between n1 and n2 divisible by 5.
#include<stdio.h> void main() { int n1,n2,i,sum=0; printf(Enter the range of numbers\n); scanf(%d%d,&n1,n2); for(i=n1;i<=n2;i++) { if(i%5==0) sum+=i; } printf(Sum of Series=%d\n, sum); getch(); }
Additional Program 10. Write a C program to simulate a simple calculator that performs arithmetic operations like addition, subtraction, multiplication and division only on integers. Error message should be reported, if any attempt is made to divide by zero. (Using switch statement)
#include<stdio.h> void main() { int a,b; float res; char ch; clrscr(); for(;;) { printf("Enter the two integers \n"); scanf("%d %d",&a,&b); printf("Enter your choice\n"); printf("+ : Addition \n - :Subtrction \n * :Multiplication \n / :Division \n"); ch=getche(); printf("\n"); switch(ch) { case '+': res = a+b; break; case '-': res = a-b; break; case '*': res=a*b; break;
Page 66
Additional Program 11. Write a C program to generate and print first N Fibonacci numbers. (Using looping constructs)
#include<stdio.h> #include<conio.h> void main() { int n,fib1,fib2,fib,i; clrscr(); printf("Enter the value of n\n"); scanf("%d",&n); fib1=0; fib2=1; printf("Fibonacci series is as follows for n=%d\n",n); if(n==1) printf("%d\n",fib1); else { printf("%d\t%d\t",fib1,fib2); for(i=3;i<=n;i++) { fib=fib1+fib2; printf("%d\t",fib); fib1=fib2; fib2=fib; } } getch(); }
Page 67
Additional Program 12. Write C user-defined functions i) To input N integer numbers into a single dimension array. ii) To compute their MEAN. iii) To compute their VARIANCE. iv) To compute their STANDARD DEVIATION. Using these functions, write a C program to input N integer numbers into a single dimension array, compute their MEAN, VARIANCE and STANDARD DEVIATION. Output the computed results with suitable headings.
#include<stdio.h> #include<math.h> float a[10], sum, mean, var, dev; int i,n; void input() { printf("Enter the elements\n"); for (i=0; i<n; i++) { scanf("%f",&a[i]); } } void compute_mean() { sum = 0; for(i=0; i<n; i++) { sum = sum + a[i]; } mean = sum/n; printf("MEAN = %f\n", mean); } void compute_var() {
Page 68
VIVA VOCE
1. What is a computer? 2. Who is the father of computer? 3. What are the characteristics of computer? 4. What are applications of computer? 5. What are the different features of computer? 6. What are the functional units of computer? 7. What are the different types of computers? 8. What are the differences between analog and digital computers? 9. What are the different input and output devices? 10. What are the different types of mouse? 11. What is an optical input device? 12. What is barcode? 13. What is barcode reader? 14. What is printer? 15. What is an algorithm? 16. What are the characteristics of an algorithm? 17. What are the notations used while writing an algorithm? Dept of CSE, CMRIT, B lore 37 Page 69
CCP Lab Manual, 10CPL16/26 18. What is flowchart? 19. List the symbols used while writing flowchart. 20. What is structure chart? 21. What is pseudocode? 22. What is software development life cycle? 23. Which steps to be followed while developing program? 24. What is testing? 25. What are the different types of testing? 26. What is ASCII? 27. What is software? What are different types of software? 28. What is hardware? 29. What is the difference between System software and Application software? 30. What is an operating system? What are the functions of operating system? 31. What is memory? Why is it required? 32. What are the different types of memory? 33. What is volatile and non-volatile memory? 34. What is cache memory? 35. What are magnetic storage devices? 36. What is a network? What are the advantages of using network? 37. What is LAN? What are the advantages and disadvantages of LAN? 38. What is WAN? What are the advantages and disadvantages of WAN? 39. What is a topology? Explain the different types of topology. 40. What are network linking devices? 41. What is Internet? What are the services of Internet? 42. What is high level language? 43. What is compiler? 44. What are tokens? 45. What are identifiers? 46. What are keywords? How many keywords is their in C programming language? 47. What is a variable? 48. What is the significance of a variable? 49. What are the rules to be followed while declaring a variable? 50. What is a constant? 51. What is a datatype? What are the different dataypes? 52. What are the basic or primary or fundamental datatypes supported by C programming language? 53. What are escape sequence characters? 54. What are backslash constants? Name some constants. 55. List the size and range of basic datatypes. 56. What is the difference between a character and string containing a single character? 57. What is the meaning of associativity of an operator? 58. What is left associativity and right associativity? 59. What is side effect? 60. What is implicit type conversion and explicit type conversion (type casting)? 61. What is precedence of an operator means? 62. List the precedence of all the types of operators along with associativity.
Page 70
CCP Lab Manual, 10CPL16/26 63. List the formatted input and output functions. 64. Describe printf() and scanf() functions. 65. What is an expression? What are the different types of expressions? 66. What is compound statement? 67. What is function? What are the advantages of functions? 68. What are the different types of functions? 69. What are the elements of functions? 70. What is a library function? 71. What is calling function and called function? 72. What is the meaning of actual parameter and formal parameter? 73. What is function prototype or function declaration? 74. What is a function call? 75. What are the various categories of user defined functions? 76. What is scope? What is the difference between local scope and global scope? 77. What is logical data? 78. Which are the logical operators? 79. Define decision making statement? 80. What is an if statement? What are the verities of if-statements? 81. What is the purpose of switch statement? Explain with syntax. 82. What is loop? List the differences between pre-test and post-test loop. 83. What is the meaning of event controlled loop and counter controlled loop? 84. What are the advantages of loops? 85. What is control statement? What are the various types of control statements available in C language? 86. Explain for loop with syntax. 87. What is the difference between while and do-while loop? 88. What are unconditional control statements? 89. What is the use of break statement? 90. What is recursion? What are the advantages and disadvantages of recursion? 91. What is an array? What is the difference between an ordinary variable and an array variable? 92. How an array will be initialized? Explain with an example. 93. How to declare an array variable? 94. What is bubble sort? 95. What is binary search? 96. What is multi-dimensional array? 97. What are the differences between recursion and iteration? 98. What is string? How strings are represented? 99. How the strings are stored in memory? 100. What is the difference between a character and string containing a single character? 101. How to read all the characters except \n using scanf()? 102. What is the disadvantage of scanf(%s, str); 103. What are various I/O functions used in case of strings? 104. How to declare an array of strings? 105. What is parallel computing? 106. What is thread? Why threads are required?
Page 71
CCP Lab Manual, 10CPL16/26 107. What is OpenMP? 108. How the data is handled in OpenMP? 109. List and explain the OpenMP Library functions. 110. What are environment variables in OpenMP?
Page 72
Page 73
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
Page 74
Page 75
Page 76
Page 77
Reference Books
1. Introduction to Computer Science, ITL Education Solutions Ltd.Pearson Education, 2004 2. Fundamentals of Computers, V.Rajaraman, 4th Edition, PHI 2005. 3. Programming Techniques through C, M.G. V. Murthy, Pearson Education, 2002 4. Let Us C ,Yashavant P. Kanetkar,11th Edition, BPB Publications, 5. Programming in ANSI C, E Balagurusamy, Tata McGraw - Hill Education, 2010 6. The Complete reference C, Herb Schildt, McGraw-Hill Osborne Media; 4th edition (April 26, 2000)
Page 78