Experiment No:23 Name of Experiment: Write a C program to using typedef. Objective: The typedef function is used to assign the new name to the datatype. So that you can use a custom name for predefined long names of the datatypes. This will not only save time but also aids in having more understandable and easy-to-read code. Algorithm: 1. Define a structure student that contains the fields name, roll_number, marks, and grade. 2. Use typedef to define a new data type Student that is an alias for struct student. 3. Declare an array students of n elements, where n is the number of students. 4. For each student, prompt the user to enter the values for name, roll_number, and marks. 5. Calculate the grade for each student based on their marks. 6. Store the values for name, roll_number, marks, and grade in the students array. 7. Display the information for each student in the students array. Flowchart: Code: #include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C Programming"); strcpy( book.author, "Nuha Ali"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407; printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); return 0; } Discussiom: typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (alias) for another data type, but does not create a new type,[1] except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.[2] As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, although it is also commonly used to provide specific descriptive type names for integer data types of varying sizes. Experiment No : 25 Experiment Name : Write a C-Program to Create a file, Close a file, Read and Write a file. Objective : The main objective of learning how to open and close files in C is to be able to read data from files, write data to files, and manipulate data stored in files. Opening a file in C allows the program to establish a connection between the file and the program, giving the program access to the contents of the file. Closing a file in C is essential because it frees up resources used by the program to access the file. Reading from a file involves retrieving data from a file and storing it in a variable or buffer in the program. Writing to a file involves storing data in a file. Learning how to read and write files in C is essential because it allows programs to store and retrieve data in a persistent and structured manner. By mastering these concepts, programmers can create programs that can handle large amounts of data and process it efficiently. Algorithm : Step 01: Begin the program. Step 02: Declare a file pointer variable fp, a character array variable name of size 20, and an integer variable age. Step 03: Declare a character array variable data and initialize it with the string "Arafat 20". Step 04: Open a file named "sample.txt" in write mode using fopen() function and assign the returned file pointer to fp. Step 05: Check if the file is created successfully. If not, print an error message and return 1 to indicate failure. Step 06: Write the string in data to the file using fputs() function. Step 07: Close the file using fclose() function. Step 08: Open the file named "sample.txt" in read mode using fopen() function and assign the returned file pointer to fp. Step 09: Read data from the file using fscanf() function. The format specifier "%s %d" reads a string followed by an integer from the file and stores them in the variables name and age respectively. Step 10: Print the read data to the console using printf() function with format specifier %s for string and %d for integer. Step 11: Close the file using fclose() function. Step 12: Print a success message to the console. Step 13: End the program. Flowchart : start declare variables fp, data, age, name create file “sample.txt” Check if opened end yes print error no writes data to file close the file reopen the file read data from it print them C-Program : close the file end #include <stdio.h> int main() { FILE *fp; char name[20]; int age; char data[] = "Arafat 20"; // create a file fp = fopen("sample.txt","w"); // check if file is created successfully if (fp == NULL) { printf("Error creating file.\n"); return 1; } // write data to file fputs(data, fp); // close file fclose(fp); // open the file for reading fp = fopen("sample.txt", "r"); // read data from file fscanf(fp, "%s %d", name, &age); // print read data to console printf("Name: %s\nAge: %d\n", name, age); // close file fclose(fp); return 0; } Output : Discussion: This code is a simple example of file input/output in C programming, and it demonstrates the basic steps involved in creating, writing to, and reading from a file. It can be used as a starting point for more complex file operations in C. By this code we will be familiar with C functions for working with files . We got a good overview on how C works with test files and what could be the possible use of file manipulating functions in C programming. Experiment No: 15 Name of Experiment: Write a C program to calculate the average using array. Objective: A c program that will calculate the average using array follows the below conditions: 1. First assign the values in the code 2. Use the formula avg=sum/n 3. Print the average value. Algorithm: Step 1: Start Step 2: Take an array A and define its values Step 3: Loop for each value of A Step 4: Add each element to 'sum' variable Step 5: After loop finishes, divide sum with number of array elements Step 6: Store that result to avg variable and display. Step 7: Stop. Flowchart: Start Declare an array & its values Use a loop for each value of the array. Add each element to 'sum' variable Divide sum with number of array elements Store that result to avg variable and display. End Input: #include<stdio.h> int main() { int a[25],n,i; float avg=0,sum=0; printf("\nEnter the numbers of terms:"); scanf("%d",&n); printf("\nEnter the numbers: \n"); for(i=1;i<=n;i++) scanf("%d",&a[i]); for(i=1;i<=n;i++) sum=sum+a[i]; avg=sum/n; printf("\nMean of enetered Numbers are: %f",avg); return 0; } Output: Enter the numbers of terms: 5 Enter the numbers: 1 2 3 4 5 average of entered Numbers are: 3.000000 Process returned 0 (0x0) execution time : 7.173 s Press any key to continue. Discussion: This program has fulfilled all the conditions and delivered output. No errors were found due to the program. So, the above program is true. Experiment no: 05 Experiment name: Write a c program to find the largest number among given three number. Objective: To make a C program will find the largest number among given three numbers and following the condition given below: 1)First assign the value in the code, 2) Take value from keyboard, 3)Use if-else statement to compare among three number and assign the largest value to the largest variable. Algorithm: Step 1 : Start the program . Step 2 : Declare variable a, b, c, largest. Step 3 : If a > b go to step 4 Otherwise go to step 5 Step 4. If a > c SET largest= a Otherwise largest = c Step 5 : If b> c SET largest = b Otherwise largest = c Step 6 : End. Flowchart Start Read a,b,c No Yes No No If b>c Print b is the largest number Yes If a>c Print c is the largest number Stop Input #include <stdio.h> Yes If a>b Print a is the largest number int main() { int a, b, c, largest; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if (num1 > num2 && num1 > num3) { largest = num1; } else if (num2 > num1 && num2 > num3) { largest = num2; } else { largest = num3; } printf("The largest number is %d\n", largest); return 0; } Output Enter three numbers:13 17 21 The largest number is 21 Discussion: After assigning value, compared the values according to conditions, largest value come as an output.After maintaining conditions from multiple side the program delivered an output.There was no error in the program. Experiment no. 02 Name of experiment : Write a c program that will take input from user and print output (int,char,float,double). Objective: we need to write a code by which we can take input in four different data types and print them without any mistakes .For that code we need an algorithm and flowchart. Algorithm: Step 1: Start. Step 2: Declare variables. Step 3: Input a,b,c,d. Step 4: Print a,b,c,d. Step 5: End. Flowchart: start start Declare variables Input a,b,c,d End Input: #include<stdio.h> int main() { int a; char b; float c; double d; printf("enter the values of int char float and double respectively \n"); scanf("%d %c %f %lf",&a ,&b,&c,&d); printf("the values of int char float and double are %d, %c ,%f, %lf",a,b,c,d); return 0; } Output: enter the values of int char float and double respectively 5 s 3.444 4.66667 the values of int char float and double are 5, s ,3.444000, 4.666670 Discussion : The code was successful in order to complete it’s task. With this code we were able to scan or input all 4 datatypes and printed those without any errors . Experiment no. 03 Name of experiment : Write a c program which will calculate(sum,sub,mul,div,mod)the number given by the user and print the output .(using function). Objective: We need to write a program by which we can calculate the summation, subtraction, multiplication and division of two numbers. We also need to use user defined function in the program to make it further useful. Because with the help of function we can call it and do the tasks as many times as we want. Algorithmn: Step 1: start Step 2 :Declare variables num1, num2, sum, sub, mul, div. Step 3:Take input from the user for num1 and num2 Step 4. Define a function for addition named "addition". Step 5. In the "addition" function, add num1 and num2 and store the result in the variable "sum". Step 6:Define a function for subtraction named "subtraction". Step 7: In the "subtraction" function, subtract num2 from num1 and store the result in the variable "sub". Step 8. Define a function for multiplication named "multiplication". Step 9:. In the "multiplication" function, multiply num1 and num2 and store the result in the variable "mul". Step 10 :Define a function for division named "division". Step 11:In the "division" function, divide num1 by num2 and store the result in the variable "div". Step 12. Call all the functions inside the main function. Step 13. Print the values of sum, sub, mul, div, mod. Step 14. End Flowchart: Flowchart: start Declare variables num1, num2, sum, sub, mul, div, mod. Take input from the user for num1 and num2 num2 Define a function for addition named "addition". In the "addition" function, add num1 and num2 and store the result in the variable "sum". Define a function for subtraction named "subtraction". In the "subtraction" function, subtract num2 from num1 and store the result in the variable "sub". Define a function for multiplication named "multiplication". In the "multiplication" function, multiply num1 and num2 and store the result in the variable "mul". Define a function fornum1 division "division". In the "division" function, divide by named num2 and store the result in the variable "div". Call all the functions inside the main function. Print the values of sum, sub, mul, div, mod. End Input: #include<stdio.h> int sum(int a,int b); int sub(int a,int b); int mul(int a,int b); double div(int a,int b); int main() { int result,a,b; printf("Calculate the summation,subtraction,multiplication and division of two numbers.\n"); scanf("%d%d",&a,&b); printf("The summation of %d & %d is %d \n",a,b,sum(a,b)); printf("The subtraction of %d & %d is %d \n",a,b,sub(a,b)); printf("The multiplication of %d & %d is %d \n",a,b,mul(a,b)); printf("The division of %d by %d is %lf \n",a,b,div(a,b)); return 0; } int sum(int a,int b) { return a+b; } int sub(int a,int b) { return a-b; } int mul(int a,int b) { return a*b; } double div(int a,int b) { return a/b; } Output: Calculate the summation,subtraction,multiplication and division of two numbers. 10 15 The summation of 10 & 15 is 25 The subtraction of 10 & 15 is -5 The multiplication of 10 & 15 is 150 The division of 10 by 15 is 0.666666 Discussion: The code was successful in it’s task. It can successfully calculate the mathematical terms between two numbers given by the user. It can constantlycalculate the summation,subtraction,multiplication and division of two numbers. Experiment No. – 07 Name of Experiment : Write a C program to to calculate the area of a triangle,circle,rectangle using function. Objective:Our objective to create a C programme which can calculate the area of triangle,circle and rectangle using function.Also this programme is intend to be familiar with the basic structure of function. Algorithm: Step 01:Start. Step 02:Define pi=3.1416. Step 03:Declare three function named tarea(),carea()& rarea(). Step 04:Inside those function,declare some variable named a,b,h&r. Step 05:Calculate the area of triangle,circle& rectangle. Step 05:Print the area of triangle,circle& rectangle. Step 06:End. Flowchart: Start Triangle Input b,h area=0.5*b*h Print area of Triangle Circle Input r area = PI *r*r Print area of Circle End Rectangle Input l,w area = l*w Print area of Rectangle Input: #include<stdio.h> #define PI 3.1416 void tarea(); void carea(); void rarea(); int main(){ printf("Calculate the area of a Triangle:\n"); tarea(); printf("Area of the triangle = %lf\n\n",tarea); printf("Calculate the area of a Circle:\n"); carea(); printf("Area of the Circle = %f\n",carea); printf("Calculate the area of a Rectangle:\n"); rarea(); printf("Area of the Rectangle = %f\n",rarea); return 0; } void tarea(){ float b,h; double tarea; printf("Enter the value of base="); scanf("%f",&b); printf("Enter the value of height="); scanf("%f",&h); tarea=0.5*b*h; } void carea(){ float r, carea; printf("Enter radius of circle\n"); scanf("%f",&r); carea = PI *r*r; } void rarea(){ float l,w,rarea; printf("Enter the length & width of the rectangle::\n"); printf("Enter the value of length="); scanf("%f\n",&l); printf("Enter the value of width="); scanf("%f\n",&w); rarea = l*w; } Discussion: In the program, we calculate the area of a triangle,circle,rectangle using function. void tarea(); void carea(); void rarea(); Three user defined function are defined to calculate triangle,circle & rectangle area. In the main() function, we call user defind function than prompt the user to enter base,height for triangle,radius for circle and length,width for rectangle.After calculation print the result. EXPERIMENT NO: 08 EXPERIMENT NAME: Write a C program to check the grade of a student. OBJECTIVE: A grading system program is generally used to check the result of students.The code is executed according to the following rules. 1. Firstly, input the number of students. 2. Use nested if else for this grading system. ALGORITHM: STEP 01: Start. STEP 02: Input mark. STEP 03: If mark >=0 and mark<=100 the code is to be executed. STEP 04: If mark >=80 then print A+. STEP 05: Else if mark >=70 then print A. STEP 06: Else if mark >=60 then print A-. STEP 07: Else if mark >=50 then print B. STEP 08: Else if mark >=40 then print C. STEP 09: Else if mark >=30 then print D. STEP 10: Else set the grade fail. STEP 11: Else invalid mark. STEP 12: End FLOWCHART: Start Input mark 0<=marks<=1 00 yes yes marks>=80 A+ NO marks>=70 yes A NO yes marks>=60 A- NO marks>=50 NO yes B yes marks>=40 C NO marks>=33 NO Fail End yes D INPUT: #include<stdio.h> int marks; printf (“Enter your mark:”); scanf(“%d”,& marks); if((marks>=0) && (marks<=100)){ if (marks>=80){ printf (“You got A+”); printf (“\n obtained mark: %d” ,marks); } else if (marks>= 70) { printf (“You got A”); printf(“\n obtained mark:%d”,marks); } else if (marks>=60){ printf (“You got A-“); printf (“\n obtained mark: %d”, marks); } else if (marks>=50){ printf(“You got B”); printf (“\n obtained mark: %d”,marks); } else if (marks>= 40){ printf (“You got C”); printf (“\n obtained mark :%d” ,marks); } else if (marks>=33) { printf (“You got D”); printf (“\n obtained mark: %d”, marks); } else{ printf (“You failed”); printf (“\n obtained mark: %d”,marks); } } else printf (“Invalid mark”); return 0; } OUTPUT: Enter your mark: 76 You got A Obtained mark: 76 Process returned 0(0*0) execution time: 4.206 s Press any key to continue. DISCUSSION: After taking input mark, the exact value came out as an output. This program has fulfilled all of the conditions and delivered output. No errors were found due the program. Hence, the C program is true. Experiment no : 10 Experiment name: Write a C Program to calculate the roots x1 and x2 of the following equation Ax2+Bx+C (6x2+8x+12) Objective: To make a C Program that will calculate the roots x1 and x2 of the following equation Ax2+Bx+C (6x2+8x+12) and follows the below co-ordinates and conditions: (i) (ii) (iii) First assign the value in the code Use integer value a=6,b=8 and c=12 Use double value for roots Algorithm: Step 1. Start Step 2. Read the coefficients of the equation, a, b and c from the user. Step 3. Calculate discriminant = (b * b) – (4 * a * c) Step 4. If discriminant > 0: 4.1: Calculate root1 = ( -b + sqrt(discriminant)) / (2 * a) 4.2: Calculate root2 = ( -b - sqrt(discriminant)) / (2 * a) 4.3: Display “Roots are real and different” 4.4: Display root1 and root2 Step 5: Else if discriminant = 0: 5.1: Calculate root1 = -b / (2 *a) 5.2: root2 = root1 5.3: Display “Root are real and equal” 5.4: Display root1 and root2 Step 6. Else: 6.1: Calculate real = -b / (2 * a) 6.2:Calculate imaginary = sqrt(-discriminant) / (2 * a) 6.3: Display “Roots are imaginary” 6.4: Display real, “±” , imaginary, “i” Step 7. Stop Flowchart: C Program : #include <math.h> #include <stdio.h> int main() { double a, b, c, discriminant, root1, root2, realPart, imagPart; printf("Enter coefficients a, b and c: "); scanf("%lf %lf %lf", &a, &b, &c); discriminant = b * b - 4 * a * c; // condition for real and different roots if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf(“Roots are real and different”); printf("root1 = %.2lf and root2 = %.2lf", root1, root2); } // condition for real and equal roots else if (discriminant == 0) { root1 = root2 = -b / (2 * a); printf(“Roots are real and equal”); printf("root1 = root2 = %.2lf;", root1); } // if roots are not real else { realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); printf(“Roots are imaginary”); printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart); } return 0; } Experiment no:12 Experiment name: Write a C program and invert temperature ( Celsius to Fahrenheit ) Objectives: The objective of this lab assignment is to develop a C program that can convert temperatures from Celsius to Fahrenheit. The program should take input from the user in Celsius and convert it to Fahrenheit using the appropriate formula. The output should be displayed in Fahrenheit with two decimal places Algorithm: Step 1: Start Step 2: Read the value of temperature to be converted from the user Step 3: Assign the value to a variable, say ‘celsius' Step 4: Initialize Fahrenheit = 0 Step 5: Fahrenheit = (1.8 * celsius ) + 32 Step 6: Display Fahrenheit Step 7: Stop Flowchart Start Read the temperature to be converted from the user: celsius Initialize Fahrenheit = 0 Fahrenheit = (1.8 * celsius ) + 32 Display the value of Fahrenheit Stop Input: #include <stdio.h> int main() { float fahrenheit, celsius; printf("Enter temperature in Celsius: "); scanf("%f", &celsius); fahrenheit = (1.8*celsius)+32; printf("The temparature in fahrenheit is%f",fahrenheit); return 0; } Output: Discussion: The conversion of Celsius to Fahrenheit is a straightforward process, and the formula used for the conversion is easy to understand. In this lab report, we have discussed the C program used for the conversion and explained how it works. We hope that this report has provided a clear understanding of the conversion process and how it can be implemented using a C program. 19.Write a c program to swap two numbers using function. Objective: The objective of this program is to swap two numbers using a function in C programming.Swapping two numbers is a common operation in programming, and it can be achieved in various ways. In this program, we will use a function to swap two numbers. The function we will use is a void function, which means it does not return any value. The function will take two integers as arguments, swap their values, and then return control to the calling function. Here's a C algorithm and flowchart for swapping two numbers using a function: Algorithm: 1. 2. 3. 4. 5. 6. 7. Start Declare the two integer variables x and y. Prompt the user to input the values of x and y. Print the values of x and y before swapping. Call the swap function and pass the addresses of x and y as arguments. Print the values of x and y after swapping. End Flowchart: c program to swap two numbers using function. #include <stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int x, y; printf("Enter two numbers: "); scanf("%d %d", &x, &y); printf("Before swapping: x = %d, y = %d\n", x, y); swap(&x, &y); printf("After swapping: x = %d, y = %d\n", x, y); return 0; } Output: Enter two numbers: 200 100 Before swapping: x = 200, y = 100 After swapping: x = 100, y = 200 Process returned 0 (0x0) execution time : 8.387 s Press any key to continue. Discussion: The swap function takes two pointers to integers as arguments and swaps the values they point to. In the main function, we declare two integers x and y , prompt the user to input their values, and print them out before swapping. We then call the swap function, passing in the addresses of x and y as arguments. Finally, we print out the values of x and y after swapping. 20.Write an algorithm and flowchart to print 1-50 or 50-1 by using recursion. Objective: The objective of this task is to write a recursive function that can print numbers from 1 to 50 or from 50 to 1, depending on the user's choice.Recursion is a programming technique that involves a function calling itself repeatedly until a specific condition is met. It is a useful technique for solving problems that can be broken down into smaller subproblems. Algorithm: 1. Start 2. Define a function printNumbers(n) to print numbers from 1 to n 3. Check if n is greater than 1 4. If yes, call the function printNumbers(n-1) 5. Print the current value of n 6. End of function 7. Call the function printNumbers(50) to print numbers 1-50 8. Define another function reverseNumbers(n) to print numbers from n to 1 9. Check if n is greater than 1 10. Print the current value of n 11. Call the function reverseNumbers(n-1) 12. End of function 13. Call the function reverseNumbers(50) to print numbers 50-1 14. End Flowchart: 20.Write a c program to print 1-50 or 50-1 by using recursion. #include <stdio.h> void printNumbersAscending(int num) { if(num > 0) { printNumbersAscending(num-1); printf("%d ", num); } } void printNumbersDescending(int num) { if(num > 0) { printf("%d ", num); printNumbersDescending(num-1); } } int main() { printf("Numbers from 1 to 50: "); printNumbersAscending(50); printf("\nNumbers from 50 to 1: "); printNumbersDescending(50); return 0; } Output: Numbers from 1 to 50: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 Numbers from 50 to 1: 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Process returned 0 (0x0) execution time : 0.457 s Press any key to continue. Discussion: In this program, we define two functions: print_numbers_1_to_50 and print_numbers_50_to_1 , which print numbers recursively from 1 to 50 and from 50 to 1, respectively. Both functions have a base case, which stops the recursion when a certain condition is met (when n reaches 51 for the first function and when n reaches 0 for the second function). In each recursive call, the current number is printed using printf, and the function is called again with the next (or previous) number, until the base case is met. Experiment No. 01 Experiment Name: Write a C-Program and print “Hello World”. Objective: Our main objective is to create a C-Program which can print a required sentence or statement. Also this program is intending to be familiar with the basic structure of C-Programming. Algorithm: Step 1: Start. Step 2: Print “Hello World” Step 3: End. Flow Chart: Start Print “Hello World” End C-Program: #include<stdio.h> int main() { printf(“Hello World”); return 0; } Output: Hello World Discussion: This program was created only to be familiar with the basic structure of C-Programming and to print a statement. No errors were found during the creation of this program. This program has fulfilled all the conditions to give a output. Thus this program is true for all integer values. Experiment No: 09 Name of Experiment: Write a C program to calculate the sum of series 1+2+3+….n. Objectives: The sum of a series in C is the result of adding all the terms of a sequence of numbers that follow a certain pattern. For example, if you have this series: 1+2+3+…+n The sum of this series is given by this formula: n * (n + 1) / 2 Algorithm: Step 1: Start. Step 2: Input n. Step 3: Sum=Sum+i. Step 4: Print Sum of Series. Step 5: End. Flow Chart: Start Input n Sum=Sum+i Print Sum of Series End Input: #include <stdio.h> int main() { int n, sum = 0; printf("Enter a positive integer: "); scanf("%d", &n); for (int i = 1; i <= n; i++) { sum += i; // sum = sum + i } printf("The sum of series 1+2+3+...+%d is %d\n", n, sum); return 0; } Outp ut: Discussion: After taking input integer “n” the exact value come out as a output.This program has fulfilled all of the conditions and deliverd output.No energy were found due the program. Experiment no: Experiment Name: Write a C program to create a simple calculator using switch. Objective: we will learn to create a simple calculator in C programming using the switch statement. Introduction: We can make a simple calculator using C language by two approaches using switch case. This program takes an arithmetic operator +, -, *, / and two operands from the user. Then, it performs the calculation on the two operands depending upon the operator entered by the user. Algorithm: Step 1 − Import the package fmt Step 2 − Start function main() Step 3 − Declare and initialize the variables Step 4 − Create the switch case statement Step 5 − Print the result using built-in function fmt.Println() flowchart: Single Expression blocks of code 1 equal to case -1 blocks of code 2 equals to block 2 blocks of code n equal to blocks n Program: #include <stdio.h> int main() { char op; double first, second; printf("Enter an operator (+, -, *, /): "); scanf("%c", &op); default printf("Enter two operands: "); scanf("%lf %lf", &first, &second); switch (op) { case '+': printf("%.1lf + %.1lf = %.1lf", first, second, first + second); break; case '-': printf("%.1lf - %.1lf = %.1lf", first, second, first - second); break; case '*': printf("%.1lf * %.1lf = break; case '/': printf("%.1lf / %.1lf = break; // operator doesn't match default: printf("Error! operator %.1lf", first, second, first * second); %.1lf", first, second, first / second); any case constant is not correct"); } return 0; } Input : number 1 = 1.5 number 2 = 4.5 choice 1: Addition of the two numbers choice 2: Subtraction of the two numbers choice 3: Multiplication of the two numbers choice 4: Division of the two numbers 2 Output: Enter an operator (+, -, *,): * Enter two operands: 1.5 4.5 1.5 * 4.5 = 6.8 Discussion: In the above two examples we have successfully compiled and executed the Golang code to make a simple calculator using switch case. Even though we can use if...else statements in the place of switch case statements, but the code written with the switch case is much cleaner and easier to write. Experiment no: 16 Name of the Experiment : Write a C program to calculate the sum of given numbers using array. Objectives: If we want to calculate the sum of given numbers using array , we need to use for loop . First , we declare an array with some numbers in it . Then we use for loop to calculate the sum of every elements of the array. Algorithmn: Step 1: Start. Step 2: Declare i,sum. Step 3: Declare arr[5] and initialize it with some values. Step 4: Initialize sum=0 . Step 5: Use for loop to calculate the sum of the elements of the array . Step 6: Display the output. Step 7 : End. Flow chart : Start sum=0 arr[5]={7,6,3,12,9} sum=sum+arr[i] Output sum Code: #include<stdio.h> int main() { int i, sum; int arr[5] = {7, 6, 3, 12, 9}; sum = 0; for(i=0;i<5;i++) { sum = sum + arr[i]; } printf("Summation of the array is : %d", sum); return 0; } Output: Discussion: In this program , we have learned about hoe to use array. The program was checked carefully to avoid any bugs. Experiment No: 18 Experiment Name: Write a c program on strlen(), strcpy(), strcat() and strcmp() and show the result. Objective: A c program that will Show the length of a string. Copy string-2 to string-1. Concatenate string-2 at the end of string-1. Compare two string. strlen(): strlen() function in C gives the length of the given string. Syntax for strlen() function is given below. size= strlen (string_name); Algorithm: 1. Start. 2. Take input from user and store it in string variable. 3. Define the size of that input and store it in size variable. 4. Print the size. 5. Stop. Flowchart: Start Read the size of input Size = size of input Print size Stop Codes: #include<stdio.h> #include<string.h> int main(){ char s1[20]; int size; printf("Enter a word less than 20 characters- \n"); scanf("%s",&s1); size=strlen(s1); printf("The length of the string is %d",s); return 0; } Output: Enter a word less than 20 charactersBangladesh The length of the string is 10 Process returned 0 (0x0) execution time : 23.479 s Press any key to continue. strcpy(): strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below. char * strcpy ( char * destination, char * source ); like, strcpy ( str1, str2) – It copies contents of str2 into str1. Algorithm: 1. Start. 2. Take two input from user. 3. Copy 2nd input to the 1st input. 4. Print 1st input. 5. Stop. Codes: #include<stdio.h> #include<string.h> int main(){ char s1[20],s2[20]; printf("Enter two word less than 20 characters- \n"); scanf("%s%s",&s1,&s2); printf("String1-%s \n String2-%s \n",s1,s2); printf("The word for String1 after copy is- \n"); strcpy(s1,s2); printf("String1-%s",s1); return 0; } Output: Enter two word less than 20 charactersBeautiful Bangladesh String1-Beautiful String2-Bangladesh The word for String1 after copy isString1-Bangladesh Process returned 0 (0x0) execution time : 22.520 s Press any key to continue. strcat(): strcat( ) function in C language concatenates two given strings. It concatenates source string at the end of destination string. Syntax for strcat() function is given below. char * strcat ( char * destination,char * source ); Algorithm: 6. Start. 7. Copy string1 at the end of string2. 8. Concatenate 2nd input at the end of 1st input. 9. Print 1st input. 10. Stop. Codes: #include<stdio.h> #include<string.h> int main(){ char s1[20]="Beautiful ",s2[20]="Day"; printf("The two word after concatenation is- \n"); strcat(s1,s2); printf("%s",s1); return 0; } Output: The two word after concatenation isBeautiful Day Process returned 0 (0x0) execution time : 0.031 s Press any key to continue. Strcmp(): strcmp( ) function in C compares two given strings and returns zero if they are same. If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value. Syntax for strcmp( ) function is given below. int strcmp ( const char * str1, const char * str2 ); strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters. Codes: #include<stdio.h> #include<string.h> int main(){ int a; char s1[20]; char s2[20]; printf("Enter two word or character to compare- \n"); scanf("%s%s",&s1,&s2); printf("After compare- \n"); a=strcmp(s1,s2); if(a==0){ printf("equal"); } else if(a>0){ printf(" s1 is greater or s2 is smaller"); } else{ printf("s1 is smaller or s2 is greater"); } return 0; } Output: Enter two word or character to compareAa After compares1 is smaller or s2 is greater Process returned 0 (0x0) execution time : 8.372 s Press any key to continue. Conclusion: From the above program we can see the usage of strlen(), strcpy(), strcat() and strcomp() on string. These codes were neat and clean and no errors were found while running these codes. So these codes are true. Experiment No. – 07 Name of Experiment : Write a C program to check the given year is leap year or not. (using function) Objective: To make a C program that will calculate and check if the given year is leap year or not and this program must be using function. To done this code we follows the below co-ordinates and conditions. i) First assign the value in the code. ii) Use integer value in the year. iii) Establish a function which check if the given year leap year or not by using function are you calling function. Algorithm: Step 1 : Start. Step 2 : Get the input year from the user. Step 3 : Assign the value to a variable, say ‘Year’. Step 4 : If (Year%4=0 AND Year%100!=0) OR Year%400=05, then go to step 5, otherwise goto step 6. Step 5 : Print Leap Year. Step 6 : If step 4 not valid print Not leap year. Step 7 : Stop. Flow Chart: Start Input Year (year%4==0&& year%100!=0) || (year % 400==0) Print Leap Year Print Not Leap Year Stop Input: #include <stdio.h> int isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return 1; } else { return 0; } } int main() { int year; printf("Enter a year: "); scanf("%d", &year); if (isLeapYear(year)) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } return 0; } Output: Discussion: In the program isLeapYear() function is defined to take an integer argument representing the year to be checked, and it returns 1 if the year is a leap year and 0 if it is not. We use a single conditional expression with the logical operators && and ||. The expression checks whether the year is divisible by 4 but not divisible by 100 (year % 4 == 0 && year % 100 != 0), or whether the year is divisible by 400 (year % 400 == 0). If either of these conditions is true, the function returns 1, indicating that the year is a leap year. Otherwise, it returns 0. In the main() function, we prompt the user to enter a year, call the isLeapYear() function to check whether the year is a leap year or not, and then print a message to the user indicating the result. Experiment No: 11 Name of experiment: Write a c-program and print the Fibonacci series. (using function) Objective: Our main objective is to print a Fibonacci series of numbers using function. The sequence of numbers starting with zero and one is a steady increasing series. Where each number is equal to the sum of the preceding two numbers. To run a C program that will print the Fibonacci series by using function follow the below condition. 1.Define a function Fibonacci and initialize first to 0 and second to 1 and display it to the console. 2.Add first and second and assign it to next and display the value of next. 3.Use the while loop to keep display the Fibonacci series until the limit entered by the user. Algorithm: Step 1: Start. Step 2: Define a function that takes an integer as an argument, which represents the number of terms to be printed in the Fibonacci series. Step 3: Inside the function, declare and initialize two variables as 0 and 1. These variables will represent the first two numbers in the Fibonacci sequence. Step 4: Use a loop to iterate through the desired number of terms in the series. In each iteration of the loop, calculate the next number in the sequence by adding the previous two numbers together. Step 5: Print out each number in the sequence. Step 6: End Flow Chart: Start First = 0 Second = 1 Input n Print a,b Next = a+b Print Next First = Second Second = Next Next = first + second Next<=n End C-Program: #include <stdio.h> void fibonacci (int n); int main () { int n; printf("Enter the limit of the fibonacci series: "); scanf ("%d",&n); fibonacci (n); return 0; } void fibonacci (int n) { int first=0, second=1, Next; printf ("Fibonacci series up to %d: ",n); printf ("%d %d ", first,second); Next= first + second; while(Next<=n) { printf ("%d ", Next); first = second; second = Next; Next = first + second; } printf ("\n"); } Output: Discussion: This program was intending to be familiar with the basic structure of function. After using input with integer data type, the exact value came out as a output. This program has fulfilled all the conditions. No errors were found during the creation of this program. Thus, this program is true for all integer values. Experiment no:13 Experiment name: To check if a given number is prime or not. Objectives: Understanding the concept of prime numbers and how to determine if a number is prime or not. Practicing the implementation of algorithms to check whether a given number is prime or not. Learning how to use functions in C to modularize code and improve its readability and reusability. Improving problem-solving skills by tackling a specific programming task and using logical thinking to come up with a solution. Enhancing programming skills by implementing the solution in C, a widely used programming language. Algorithm: To Find Prime Number. STEP 1: Take num as input. STEP 2: Initialize a variable temp to 0. STEP 3: Iterate a “for” loop from 2 to num/2. STEP 4: If num is divisible by loop iterator, then increment temp. STEP 5: If the temp is equal to 0, Return “Num IS PRIME”. Else, Return “Num IS NOT PRIME”. Flow chart: Output: #include<stdio.h> int check_prime(int); main() { int n, result; printf("Enter an integer to check whether it is prime or not.\n"); scanf("%d",&n); result = check_prime(n); if ( result == 1 ) printf("%d is prime.\n", n); else printf("%d is not prime.\n", n); return 0; } int check_prime(int a) { int c; for ( c = 2 ; c <= a - 1 ; c++ ) { if ( a%c == 0 ) return 0; } return 1; } Discussion: In conclusion, the provided code accomplishes its objective of checking whether a given number is prime or not using a function. The code is relatively simple and easy to understand, making it suitable for educational purposes. However, it could be improved by adding input validation to ensure that the user enters a positive integer. Additionally, more efficient algorithms for checking primality could be used for larger numbers. Experiment no:21 Experiment name: Write a c-program to calculate sum by using recursion. Objectives: In this program, we will learn to find the sum of natural numbers using a recursive function. To understand this example, we should have the knowledge of the following C-programming topics: 1. C User-defined functions. 2. C Recursion. The positive numbers 1, 2, 3... Are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number. Algorithm: Step-1: Start. Step-2: Take input n for main function. Step-3:Take n=20. Step-4: Print first 10 natural number addition by using recursion. Step-5: Print recur(n). Step-6: Take input n again for user define function. Step-7: Take if condition where if (n! = 0). Step-8: Then return n + recur(n-1). Flowchart: Start Int recur(int n) Return=0 True n!=0 False End Input: #include<stdio.h> int recur(int n); int main(){ int n=20; printf("First 20 natural number addition by using recursion.\n"); printf("The addition is= %d",recur(n)); return 0; } int recur(int n) { if(n!=0){ return n+recur(n-1); } } Return =n+recur(n-1) Output: Discussion: Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is usually much slower. That being said, recursion is an important concept. It is frequently used in data structure and algorithms. For example, it is common to use recursion in problems such as tree traversal. Experiment No : 17 Name of the Experiment : Write a C program to take input string from keyboard. Objectives : In C programming, to take input string from keyboard, at very fast we need to include the header file for string which is #include<string.h>. Then we use declare a string variable, use gets() to take input string and use puts() to print that string. Algorithm : Step 1 : Start. Step 2 : Declare string variable ch[100]. Step 3 : Take input string using gets() and store it in ch. Step 4 : Display the output using puts(). Step 5 : End. Flow Chart : Start Input ch Output ch End Code : #include<stdio.h> #include<string.h> int main ( ) { char ch[100]; printf("Enter a string : "); gets(ch); puts(ch); return 0; } Output : Discussion : This program shows us how to take input string in C programming and output it.The program was checked carefully to avoid any bugs. Experiment No. 10 Experiment Name: Write a C-Program to calculate factorial of a number using function. Objective: A function is a group of statements that together perform a task.We need functions in C programming and even in other programming languages due to the numerous advantages they provide to the developer. This program is intending to be familiar with the basic structure of function. Also our main objective is to create a C-Program which can calculate factorial of a number through using function. Algorithm: Step 01: Start. Step 02: Declare a function named ‘factorial’ that takes an integer value ‘n’. Step 03: Inside the function, declare a variable named ‘result’ and initialize it to 1. Step 04: Use a for loop to iterate from 1 to ‘n’ incrementing by 1 each time. Step 05: Inside the loop, multiply ‘result’ the loop variable. Step 06: Return ‘result’ from the function. Step 07: In main function, input a number. Step 08: Read user input and store it in an integer variable named ‘num’. Step 09: Call the factorial function with num as the argument and store the returned value in a variable named ‘fact’. Step 10: Print the value of ‘fact’. Step 11: End. Flow Chart: Start Set result = 1 Result *= i Input the number fact= factorial (x) Print factorial End Input: #include <stdio.h> int factorial(int x) { if (x == 0 || x == 1) { return 1; } else { return x * factorial(x - 1); } } int main() { int x; printf("Enter the number : "); scanf("%d", &x); printf("The factorial of %d is:\n %d\n", x, factorial(x)); return 0; } Output: Discussion: This program was intending to be familiar with the basic structure of function. After using input with integer data type, the exact value came out as a output. This program has fulfilled all the conditions. No errors were found during the creation of this program. Thus, this program is true for all integer values. Experiment no: 22 Experiment name: Write a c-program to store students information using structure. Objective: Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.). You can create a structure by using the struct keyword and declare each of its members inside curly braces. To access the structure, you must create a variable of it. Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable. Algorithm: Step 1: Start . Step 2: Declare variable name[50] (char),roll(int),marks(float). Step 3: Declare structure name. Step 4: Get input name ,roll & marks from keyboard. Step 5: Print name ,roll & marks Step 6: End. Flowchart: Start Declare name,roll & marks Declare structure name Get input from keyboard Name ,roll & marks Print name,roll & marks End Code: #include <stdio.h> struct student { char name[50]; int roll; float marks; }; int main() {struct student s; printf("Enter The Information of Students :\n\n"); printf("Enter Name : "); scanf("%s",s.name); printf("Enter Roll No. : "); scanf("%d",&s.roll); printf("Enter marks : "); scanf("%f",&s.marks); printf("\nDisplaying Information\n"); printf("Name: %s\n",s.name); printf("Roll: %d\n",s.roll); printf("Marks: %.2f\n",s.marks); return 0; } Output: Discussion: From this code we get a basic concept of structure. Experiment no: 12 Experiment Name : Write a C- program using union. Objective : To make a C-Program that will store different data type in same memory location.Which can define a union with many members, but at any given instance of time only one member can contain value. Algorithm : Step-1: Start the program Step-2: Declare Union Char name,age,salary Step-3: Union Employee employee Step-4: Memory occupied by employee Step-5: End Flowchart: Start Input char name[32]; int age; float salary Union Employee employee Print Memory occupied by Employee (variable size of employee) Stop Input: #include <stdio.h> union Employee { char name[32]; int age; float salary; }; int main(){ union Employee employee; printf("Memory occupied by Employee variable : %d\n", sizeof(employee)); return 0; } Output: Memory occupied by Employee variable : 32 Discussion: Above program shows that we are storing different member variables of a union in same memory location. However a union variable can only retain the value of most recently updated member variable. A variable of type Employee union can store either a string(name of employee) value , an integer(age of employee)value or a float(salary of employee) value at at time but not more than one member. A union variable will only get enough memory to store the largest member of union.For a variable of union Employee will occupy 32 bytes of memory to store the largest member which is name of employee.