Laboratory Manual for COMPUTER PROGRAMMING AND UTILISATION (2110003) Bachelor of Engineering SEM I 2014-2015 Shree Swami AtmanandSaraswati Institute of Technology Shree Swami AtmanandVidyaSankul, Kapodra, Varachha Road, Surat – 395006 www.ssasit.org Computer Programming and Utilisation LAB Manual SSASIT, Surat INDEX Sr. No. 1. 2. 3. Name Of Practical PRACTICAL-SET—1 1. Write a program to print ―HELLO FRIENDS‖. 2. Write a program that reads two nos. from key board and gives their addition, subtraction, multiplication, division and modulo. 3. Write a program to convert days into months and days 4. Write a program to solve Quadratic Equation. 5. Write a program to select & print the largest of the three nos. using Nested-If-Else PRACTICAL-SET—2 6. Write a program to display multiplication table 7. Write a program to print 1+1/2+1/3+1/4+………+1/N series. 8. Write a program to find sum of all integers greater than 100 & less than 200 and are divisible by 5. 9. The distance between two cities (In KM) is input through key board. Write a program to convert and print this distance in meters, feet, inches & centimeters. 10. Write a program to find sum of first N odd numbers. Ex. 1+3+5+7+………..+N. PRACTICAL-SET-3 11. Write a program for use of putchar( ) and getchar( ) function. 12. Program to print Patterns. * ** *** **** 13. 1 2 3 4 5 2345 345 45 5 14. AAAAA BBBB CCC DD E Page No. Date Sign Grade Computer Programming and Utilisation LAB Manual 15. 4. 5. 6. 7. 1 01 101 0101 PRACTICAL-SET-4 16. Write a program to print Fibonacci series. 0,1,1,2,3,5,……N 17. Write a program to reverse the digit. 18. Add, subtract and multiply two nos. using switch statement 19. Write a program to add two matrixes 20. Write a program to given no in ascending order. 21. W.A.P to read array of integers and print it in reverse order PRACTICAL-SET-5 22. Write a program to count total words in text. 23. Find length of string using strlen( ) function 24. Write a program to copy one string to another string. 25. Write a program to join two strings. 26. Write a program convert character into Toggle character. 27. Find given string is palindrome or not using string library function PRACTICAL-SET-6 28. Write a function program to add first N numbers. 29. Write a function find out maximum out of three numbers. 30. Write a function power that computes x to the power y for integer x and y and returns double type value. 31. Write a program to find factorial of a number using recursion. 32. Write a program that used user defined function Swap ( ) and interchange the value of two variable. 33. Write a function prime that return 1 if it„s argument is prime and return 0 otherwise. 34. Write a calculator program(add,subtract,multiply,divide). Prepare user defined function for each operation. PRACTICAL-SET-7 35. Define a structure type, personal, that would contain person name, date of joining and salary. Using this structure, write a program to read this information for one person from the key board and print the same on the screen. SSASIT, Surat Computer Programming and Utilisation LAB Manual 36. 8. 9. 10. Define a structure called cricket that will describe the following information: a. Player name b. Team name c. Batting average 37. Write a function to enter rollno, marks of the three subject for 3 student and find total obtained by each student PRACTICAL-SET-8 38. Write a program using pointer and function to determine the length of string. 39. Write a program using pointer to compare two strings. 40. Write a program using pointer to concate two strings 41. Write a program using pointer to copy one string to another string. 42. Write a program using pointer to read an array if integer and print element in reverse order. PRACTICAL-SET-9 43. Write a program that uses a table of integers whose size will be specified interactively at run time. 44. Write a program to store a character string in block of memory space created by malloc and then modify the same to store a large string. PRACTICAL-SET-10 45. A program to illustrate reading files contents. 46. A program to illustrate the use of fgets( ). 47. A program to illustrate the use of fputc ( ) and fputs( ). SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 1 AIM: Write a program to print ―HELLO FRIENDS. LOGIC: This is very basic program of C. First include basic header files and then start main () function. Write printf function want to print. Syntax of printf(): printf(― ‖ , ); OUTPUT: 1 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 2 AIM: Write a program that reads two nos. from key board and gives their addition, subtraction, multiplication, division and modulo. LOGIC: Declare 2 variables. Use “scanf” to take input from users. Use the logic to perform addition, subtraction, multiplication and division of the 2 numbers. The modulo operator (%) gives us the reminder when division is performed between 2 integer numbers. OUTPUT: 2 Computer Programming and Utilisation LAB Manual EXPERIMENT – 3 AIM: Write a program to convert days into months and days LOGIC: Take number of days from user. Use binary operator(i.e.+-,% etc) to find result Print result using printf() function Note: Consider no of days in a month=30 3 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 4 AIM: Write a program to solve Quadratic Equation. LOGIC: A Quadratic Equation of the form 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0 Use following formula to find root of the equation −𝑏 ± 𝑏 2 − 4𝑎𝑐 𝑥= 2𝑎 Take value of variable a, b & c as input from user and put it in given equation to find the Roots of a quadratic equation 𝑑 = 𝑏 2 − 4𝑎𝑐 −𝑏 + 𝐷 𝑥1 = 2𝑎 −𝑏 − 𝐷 𝑥2 = 2𝑎 Note: To calculate Square root use sqrt function which is defined in math.h library. You must include this header file before using sqrt To find root of equation 𝑥 2 + 9𝑥 + 20 = 0 INPUT: Enter a: 1 Enter b: 9 Enter c: 20 OUTPUT: First Root is: - 4 Second Root is:- 5 4 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 5 AIM: Write a program to select & print the largest of the three nos. using Nested-If-Else LOGIC: Take three numbers as input from user and use the below logic to find maximum and minimum of the numbers. Syntax of nested if if(){ if(){ }else{ } }else{ } OUTPUT: 5 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 6 AIM: Write a program to display multiplication table LOGIC: Take a number from user. Use while loop (or any other) to Multiply the given number (table) with value of 'i' which increments from 1 to 10. while(condition){ //Loop body } OUTPUT: 6 Computer Programming and Utilisation LAB Manual EXPERIMENT – 7 SSASIT, Surat 1 1 1 1 2 3 4 𝑁 AIM: Write a program to print 1 + + + + ⋯ + LOGIC: Take no. of terms of series from user. 1.0 Now apply 𝑠𝑢𝑚 = 𝑠𝑢𝑚 + ; // where sum and i are variable 𝑖 Syntax of for loop for(initialization; condition; increment/decrement) { //Loop body } OUTPUT: 7 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 8 AIM: Write a program to find sum of all integers greater than 100 & less than 200 and are divisible by 5. LOGIC: Take start value and end value from user. A number is divisible by 5 only when its unit From above logic find out series then sum them OUTPUT: 8 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 9 AIM: The distance between two cities (In KM) is input through key board. Write a program to convert and print this distance in meters, feet, inches & centimetres. LOGIC: Take distance between two cities in KM. Now apply conversion logic i.e. 1km=39370 inch 1km=3281 feet 1km=100000 cm OUTPUT: 9 Computer Programming and Utilisation LAB Manual EXPERIMENT – 10 SSASIT, Surat AIM: Write a program to find sum of first N odd numbers. Ex. 1 + 3 + 5 + 7 + ⋯+ 𝑁 LOGIC: Take no. of terms of series from user. Use loop to print and finding sum of the numbers. Increment should be of 2 after each iteration. Print sum. OUTPUT: 10 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 11 AIM: Write a program for use of putchar( ) and getchar( ) function. LOGIC: C provides other ways to read and write single characters. In particular, we can use the getchar() and putchar() functions instead of calling scanf and printf. putchar() writes a single character: putchar (ch); Each time getchar is called, it reads one character, which it returns. In order Save this character, we must use assignment to store it in a variable: ch = getchar(); /* reads a character and stores it in ch */ getchar actually returns an int value rather than a char value (the reason will be discussed in later chapters). As a result, it's not unusual for a variable to have type int rather than char if it will be used to store a character read by getchar. Like scanf, getchar doesn't skip white-space characters as it reads. Using getchar and putchar (rather than scanf and printf) saves lime when theprogram is executed; getchar and putchar are fast for two reasons. First, they're much simpler than scanf and printf, which are designed to read and write many kinds of data in a variety of formats. Second, getchar and putchar are usual implemented as macros for additional speed. getchar() has another advantage over scanf: because it returns the character that it reads, getchar lends itself to various C idioms, including loops that search for a character or skip over all occurrence of character OUTPUT: 11 Computer Programming and Utilisation LAB Manual EXPERIMENT – 12 AIM: Write Program to print Patterns. * ** *** **** LOGIC: Take Number of rows from Now use any loop to print pattern. Syntax of for loop for(initialization ;condition ;increment/decrement) { //Loop body } Syntax for while loop while(test condition) { //loop body } OUTPUT: 12 SSASIT, Surat Computer Programming and Utilisation LAB Manual EXPERIMENT – 13 AIM: Write Program to print Patterns. 12345 2345 345 45 5 LOGIC: Take Number of rows from user. Now use any loop to print pattern. OUTPUT: 13 SSASIT, Surat Computer Programming and Utilisation LAB Manual EXPERIMENT – 14 AIM: Write a program to print following pattern. AAAAA BBBB CCC DD E LOGIC: Take Number of rows from user Now use any loop to print pattern. Use ASCII value of letters to print ASCII value of A is 65, B is 66, C is 67, …, Z is 90 OUTPUT: 14 SSASIT, Surat Computer Programming and Utilisation LAB Manual EXPERIMENT – 15 AIM: Write a program to print following pattern. 1 01 101 0101 LOGIC: Take Number of rows from Now use any loop to print pattern. OUTPUT: 15 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 16 AIM: Write a program to print Fibonacci series. 0, 1, 1, 2, 3, 5,……, N LOGIC: Numbers of Fibonacci sequence are known as Fibonacci numbers. In mathematics it is defined by recurrence relation. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms, For example 5 = 2+ 3 (addition of 2, 3). This sequence has many applications in mathematics and Computer Science. Take Number of terms from user. Syntax of for loop for(initialisation ;condition ;increment/decrement) { //Loop body } Syntax for while loop while(test condition) { //loop body } OUTPUT: 16 Computer Programming and Utilisation LAB Manual EXPERIMENT – 17 AIM: Write a program to reverse the digit. LOGIC: Take any number from user. Now use % operator and any loop for finding result. Syntax: while(test condition) { //body of loop } OUTPUT: 17 SSASIT, Surat Computer Programming and Utilisation LAB Manual EXPERIMENT – 18 AIM: Add, subtract and multiply two nos. using switch statement LOGIC: Take operator from user. Syntax for switch case switch( ) { case ‗+‘: //logic for sum break; case ‗-‘: //logic for subtraction break; case ‗*‘: //logic for multiplication break; case ‗/‘: //logic for Division break; } OUTPUT: 18 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 19 AIM: Write a program to add two matrixes. LOGIC: Addition of two matrices: Rule: Addition of two matrices is only possible if both matrices are of same order. Suppose two matrices A and B is of same size m X n Sum of two matrices is defined as (A + B)ij = Aij + Bij Where 1 ≤ i ≤ m and 1 ≤ j ≤ n For example: Suppose two matrices A and B of size of 2 X 3 is as follow: 𝐴= B= A+B= 3+1 2+2 3 2 2 8 5 4 1 3 4 9 3 −6 2+3 5+4 8 + 3 4 + −6 OUTPUT: 19 = 4 5 9 4 11 −2 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 20 AIM: Write a program to given no in ascending order. LOGIC: Ask number of terms from user. Now apply sorting logic to sort in increasing (ascending) Order. Hint: You will have to use nested looping concept for this. OUTPUT: Enter total no. of element: 5 Enter 5 elements: 9 1 5 6 2 Ascending order:: 1 2 5 6 9 20 Computer Programming and Utilisation LAB Manual EXPERIMENT – 21 AIM: W.A.P to read array of integers and print it in reverse order. LOGIC: Syntax of array declaration: Storage _class data _type arrayname[size]; OUTPUT: Enter size of Array: 5 Enter 5 elements: 25 13 51 69 44 Reverse order:: 44 69 51 13 25 21 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 22 AIM: Write a program to count total words in text. LOGIC: Here count variable is incremented as and when white space is detected. OUTPUT: 22 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 23 AIM: Find length of string using strlen( ) function LOGIC: The C library function strlen(char *str) computes the length of the string „str‟ up to but not including the terminating null character. OUTPUT: 23 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 24 AIM: Write a program to copy one string to another string. LOGIC: Two string variables are declared and first string is copied character by character to the second one till null character (\0) is detected. OUTPUT: 24 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 25 AIM: Write a program to join two strings LOGIC: Two strings are declared to store the strings and third string is declared of size twice the size of the first two strings. String1 is first copied character by character and then second string is copied character by character to the third string till null character is detected. OUTPUT: 25 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 26 AIM: Write a program convert character into Toggle character. LOGIC: To toggle the character means all UPPERCASE characters are converted to lowercase and vice-versa. Each character has an ASCII value difference of 32 so accordingly value 32 is added or deducted depending on whether the case of the character is upper or lower. OUTPUT: 26 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 27 AIM: Find given string is palindrome or not using string library function LOGIC: A string is called palindrome if the reverse of that string is same as the original string. At first we copy the entered string into a new string, and then we reverse the new string and then compare it with original string. If both of them have same sequence of characters i.e. they are identical then the entered string is a palindrome otherwise not. OUTPUT: 27 Computer Programming and Utilisation LAB Manual EXPERIMENT – 28 AIM: Write a function program to add first N numbers. LOGIC: Take maximum value of series from user. Apply sum of n terms formula of arithmetic progression OUTPUT: 28 SSASIT, Surat Computer Programming and Utilisation LAB Manual EXPERIMENT – 29 AIM: Write a function find out maximum out of three numbers. LOGIC: Input 3 number from user Syntax for declaration of user defined function: <Return type> function _name( argument) { //Function body } OUTPUT: 29 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 30 AIM: Write a function power that computes x and returns double type value. LOGIC: Syntax for declaration of user defined function: OUTPUT: 30 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 31 AIM: Write a program to find factorial of a number using recursion. LOGIC: Recursion: When a function calls itself again and again is known as recursion. Factorial is represented using '!', so five factorial will be written as (5!), n factorial as (n!). Also defined as one i.e. 0! = 1. Factorial of negative numbers not defined. OUTPUT: 31 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 32 AIM: Write a program that used user defined function Swap ( ) and interchange the value of two variables LOGIC: Take two numbers You may do swapping without using third variable a = a + b; b = a - b; a = a - b; OR x = x ^ y; y = x ^ y; x = x ^ y; Where ^ is XOR Operator. Using third Variable temp= x; x = y; y = temp; OUTPUT: 32 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 33 AIM: Write a function prime that return 1 if it„s argument is prime and return 0 otherwise. LOGIC: Prime Number: A number is prime, if it is divisible only by one or itself. Remember 2 is the only even and also the smallest prime. First few prime numbers are 2, 3, 5, 7, 11, 13, 17....etc. Prime numbers have many applications in computer science and mathematics. A number greater than one can be factorized into prime numbers. OUTPUT: 33 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 34 AIM: Write a calculator program (add, subtract, multiply, divide). Prepare user defined function for each functionality. LOGIC: Syntax: Function Declaration, <Return_type> function _name (Parameter List){ //Function body } Calling of function:: function_name (Parameter_list); OUTPUT: 34 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 35 AIM: Define a structure type, personal, that would contain person name, date of joining and salary. Using this structure, write a program to read this information for one person from the key board and print the same on the screen. LOGIC: Declare a structure Syntax is: struct tagname { // Memer1; // member 2; //Member n; } structure Variable; Access structure member using .(dot operator) Syntax is:: structure_variable. Member name; OUTPUT: 35 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 36 AIM: Define a structure called cricket that will describe the following information: a. Player name b. Team name c. Batting average LOGIC: Syntax of structure declaration: struct tagname { Member 1………. Member 2………. ………………….. }str_variable; Taking value from keyboard in structure variable, str_variable.membername OUTPUT: 36 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 37 AIM: Write a function to enter roll no, marks of the three subjects for 3 student and find total obtained by each student LOGIC: Declare structure. Make a function to take input by keyboard. Apply str_var[i].sum+=str_var[i].sub[j]; OUTPUT: 37 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 38 AIM: Write a program using pointer and function to determine the length of string. LOGIC: Input string from user. Define a user defined function to count number of character in the given string until „\0‟ .you has to increment by 1 value of count each time. Function return count(an integer value). Call this function in main() to find length of the given string. OUTPUT: 38 Computer Programming and Utilisation LAB Manual EXPERIMENT – 39 AIM: Write a program using pointer to compare two strings. LOGIC: Input two string from keyboard. Use a for loop to check until null(„\0‟) of two string. for(;*p!='\0' || *q!='\0';*p++,*q++){ //your logic here } OUTPUT: 39 SSASIT, Surat Computer Programming and Utilisation LAB Manual EXPERIMENT – 40 AIM: Write a program using pointer to concate two strings LOGIC: Input two string from keyboard. Add second string to the end of first string. Display on output screen OUTPUT: 40 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT –41 AIM: Write a program using pointer to copy one string to another string. LOGIC: Input one string from keyboard. Define a function to copy given string in new string variable. Display the new string variable. OUTPUT: 41 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 42 AIM: Write a program using pointer to read an array of integer and print element in reverse order. LOGIC: Syntax Of Declaration array: Storage _class array_name[size]; Input size of array by user. Take integer numbers from user. Store in array of integer. Apply logic to reverse the numbers. OUTPUT: 42 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 43 AIM: Write a program that uses a table of integers whose size will be specified interactively at run time. LOGIC: C dynamic memory allocation refers to performing dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free. Function malloc() calloc() realloc() free() Syntax Stand for No of argument Return value Description allocates the specified number of bytes allocates the specified number of bytes and initializes them to Zero increases or decrease the size of the specified block of memory. Reallocates it if needed releases the specified block of memory back to the system malloc() calloc() void *malloc(size_t size); void *calloc(size_t nelements, size_t bytes); Bytes of memory allocation Blocks of Memory -Allocation 1 2 void pointer (void *) void pointer (void *) For Example: int *ptr = malloc(10 * sizeof (int)); Allocates (10*2=20) 20 bytes of memory and assign first address to pointer variable ptr. free(): is used to release the memory. 43 Computer Programming and Utilisation LAB Manual OUTPUT: 44 SSASIT, Surat Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 44 AIM: Write a program to store a character string in block of memory space created by malloc() and then modify the same to store a large string. LOGIC: C dynamic memory allocation refers to performing dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc(), realloc(), calloc() and free(). For Example: int *ptr = malloc(10 * sizeof(int)); Allocates (10*2=20) 20 bytes of memory and assign first address to pointer variable ptr. free(); is used to release the memory. realloc(); The function realloc() reallocates a memory block with a specific new size. If you call realloc() the size of the memory block pointed to by the pointer is changed to the given size in bytes. This way you are able to expand and reduce the amount of memory you want to use (if available of course.) Usage of realloc(): void * realloc ( void * ptr, size_t size ); Parameters: A pointer (ptr) to a previously allocated block of memory. (The memory was previously allocated with malloc(), calloc() or realloc() functions.) A new size in bytes for the new memory block. Return value: Will return a pointer to the reallocated memory block. If the function fails then a NULL pointer is returned. OUTPUT: 45 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 45 AIM: A program to illustrate reading files‟ contents. LOGIC: When we request the operating system to a file, what we get back is a pointer to the structure FILE. That is why; we make the following declaration before ending the file. FILE *fp; open( ) will open a file “SSASIT.txt” in „read‟ mod e, which tells the compiler that we would be reading the contents of the file. Note that “r” is a string and not a character; hence the double quotes and not single quotes. Once the file has been opened for reading using fopen( ), the file‟s contents are brought into memory and a pointer points to the very first character. To read the file‟s contents from memory there exists a function called fgetc( ). This has been used in our sample program through, ch = fgetc(fp) ; When we have finished reading from the file, we need to close it. This is done using the function fclose() through the statement, fclose ( fp ); //Where fp is file pointer fopen(―location of file‖, ―Mode‖) Mode May be r(read mode),w(write mode)etc OUTPUT: 46 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 46 AIM: A program to illustrate the use of fgets( ). LOGIC: The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. Syntax of fgets() function: char *fgets(char *str, int n, FILE *stream) str -- This is the pointer to an array of chars where the string read is stored. n -- This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used. stream -- This is the pointer to a FILE object that identifies the stream where characters are read from. OUTPUT: 47 Computer Programming and Utilisation LAB Manual SSASIT, Surat EXPERIMENT – 47 AIM: A program to illustrate the use of fputc( ) and fputs( ). LOGIC: Syntax of fputs(): int fputs ( const char * str, FILE * stream ); The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. Arguments: Str: C string with the content to be written to stream. Stream: Pointer to a FILE objects that identifies an output stream. Syntax of fputc: int fputc (int character, FILE * stream ); Writes a character to the stream and advances the position indicator. The character is written at the position indicated by the internal position indicator of the stream, which is then automatically advanced by one. Argument Character The int promotion of the character to be written. The value is internally converted to an unsigned char when written. Stream Pointer to a FILE objects that identifies an output stream. Return Value On success, the character written is returned. If a writing error occurs, EOF is returned and the error indicator (ferror) is set. OUTPUT: 48