0% found this document useful (0 votes)
18 views18 pages

CPR Write-Ups (10,11 and 12)

The document outlines various C programming experiments, including algorithms and code for functions such as power calculation, arithmetic operations, and area calculations. It also covers concepts of call by value and call by reference, along with examples and explanations for each. Additionally, it includes post-lab questions and their answers related to function outputs and error handling.

Uploaded by

Aams Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views18 pages

CPR Write-Ups (10,11 and 12)

The document outlines various C programming experiments, including algorithms and code for functions such as power calculation, arithmetic operations, and area calculations. It also covers concepts of call by value and call by reference, along with examples and explanations for each. Additionally, it includes post-lab questions and their answers related to function outputs and error handling.

Uploaded by

Aams Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Experiment 10

Algorithm:

1.​ Start
2.​ Define a function power(a, b) that takes two parameters: base a and exponent b
3.​ Initialize a variable result to 1
4.​ For i = 1 to b:
○​ Multiply result by a
5.​ Return result
6.​ In the main function:
○​ Declare variables for base, exponent, and result
○​ Input values for base and exponent
○​ Call the power function and store the result
○​ Display the result
7.​ End

MAKE FLOWCHART ON YOUR OWN

Code:

#include <stdio.h>

// Function to calculate a raised to power b


int power(int a, int b) {
int result = 1;

// Handle special cases


if (b == 0)
return 1;

// Calculate a^b using loop


for (int i = 1; i <= b; i++) {
result = result * a;
}

return result;
}

int main() {
int base, exponent, result;

// Input base and exponent


printf("Enter base: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);

// Call power function


result = power(base, exponent);

// Display the result


printf("%d raised to the power %d is: %d\n", base, exponent, result);

return 0;
}

Post Lab Answers:

(1) Output of the C program:

#include <stdio.h>
int check(int ch);
void main() {
int i = 20, c;
c = check(i);
printf("\n%d", c);
}
int check(int ch) {
if (ch >= 50)
return (100);
else
return (50);
}

The output of this program is: 50

Explanation:

1.​ In the main() function, i is initialized to 20


2.​ The function check(i) is called with argument 20
3.​ Inside the check() function, 20 is compared with 50
4.​ Since 20 is not greater than or equal to 50, the else part executes
5.​ The function returns 50
6.​ This value is assigned to variable c in the main() function
7.​ The printf() statement prints the value of c, which is 50
(2) Errors in the following function:
sqr(a) {
return (a*a);
}

Errors:

1.​ Missing return type for the function (should be int, float, double, etc.)
2.​ Missing data type for parameter a

Corrected function:

int sqr(int a) {
return (a*a);
}

(3) Write the following functions:

(a) Function with no argument and no return value:


void greet() {
printf("Hello, World!\n");
}
(b) Function with no argument and a return value:
int getCurrentYear() {
return 2025; // Returns the current year
}

(c) Function with arguments and no return value:


void displaySum(int a, int b) {
printf("Sum of %d and %d is: %d\n", a, b, a+b);
}

(d) Function with arguments and a return value:


int multiply(int a, int b) {
return a * b;
}

(1) Program to add two numbers using user-defined function:

#include <stdio.h>

// Function to add two numbers


int addNumbers(int a, int b) {
return a + b;
}
int main() {
int num1, num2, sum;

// Input two numbers


printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

// Call function to add numbers


sum = addNumbers(num1, num2);

// Display the result


printf("Sum of %d and %d is: %d\n", num1, num2, sum);

return 0;
}

(2) Program to find area and perimeter of a circle using user-defined function:

#include <stdio.h>
#define PI 3.14159

// Function to calculate area of a circle


float calculateArea(float radius) {
return PI * radius * radius;
}

// Function to calculate perimeter (circumference) of a circle


float calculatePerimeter(float radius) {
return 2 * PI * radius;
}

int main() {
float radius, area, perimeter;

// Input radius
printf("Enter the radius of the circle: ");
scanf("%f", &radius);

// Calculate area and perimeter using functions


area = calculateArea(radius);
perimeter = calculatePerimeter(radius);

// Display results
printf("Radius of the circle: %.2f units\n", radius);
printf("Area of the circle: %.2f square units\n", area);
printf("Perimeter of the circle: %.2f units\n", perimeter);

return 0;
}

(3) Program to perform arithmetic operations using switch case and user-defined
functions:

#include <stdio.h>

// Function to add two numbers


float add(float a, float b) {
return a + b;
}

// Function to subtract two numbers


float subtract(float a, float b) {
return a - b;
}

// Function to multiply two numbers


float multiply(float a, float b) {
return a * b;
}

// Function to divide two numbers


float divide(float a, float b) {
if (b == 0) {
printf("Error: Division by zero is not allowed.\n");
return 0;
}
return a / b;
}

int main() {
float num1, num2, result;
char operation;

// Input two numbers


printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter second number: ");
scanf("%f", &num2);
// Input operation choice
printf("Enter operation (+, -, *, /): ");
scanf(" %c", &operation); // Note the space before %c to consume any whitespace

// Perform operation based on user choice using switch case


switch (operation) {
case '+':
result = add(num1, num2);
printf("%.2f + %.2f = %.2f\n", num1, num2, result);
break;

case '-':
result = subtract(num1, num2);
printf("%.2f - %.2f = %.2f\n", num1, num2, result);
break;

case '*':
result = multiply(num1, num2);
printf("%.2f * %.2f = %.2f\n", num1, num2, result);
break;

case '/':
result = divide(num1, num2);
if (num2 != 0) {
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
}
break;

default:
printf("Error: Invalid operation selected.\n");
}

return 0;
}

(4) Program to change case of an alphabet using user-defined function:

#include <stdio.h>

// Function to change case of an alphabet


char changeCase(char ch) {
if (ch >= 'A' && ch <= 'Z') {
// Convert uppercase to lowercase
return ch + 32;
} else if (ch >= 'a' && ch <= 'z') {
// Convert lowercase to uppercase
return ch - 32;
} else {
// Return as is if not an alphabet
return ch;
}
}

int main() {
char character, result;

// Input a character
printf("Enter an alphabet: ");
scanf("%c", &character);

// Check if the input is an alphabet


if ((character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z')) {
// Change case using the function
result = changeCase(character);

// Display the result


printf("Original character: %c\n", character);
printf("After changing case: %c\n", result);
} else {
printf("Error: Input is not an alphabet.\n");
}

return 0;
}
Experiment 11

i) Call by Value

Algorithm:

1.​ Start
2.​ Define a function swap(int a, int b) that takes two integers as parameters
3.​ Inside the function, swap the values using a temporary variable
4.​ Print the values before and after the swap function call in the main function
5.​ End
Code:

#include <stdio.h>

void swap(int a, int b) {


int temp;
printf("Before swapping in function: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swapping in function: a = %d, b = %d\n", a, b);
}

int main() {
int a = 10, b = 20;

printf("Before function call: a = %d, b = %d\n", a, b);


swap(a, b);
printf("After function call: a = %d, b = %d\n", a, b);

return 0;
}

(ii) Call by Reference

Algorithm:

1.​ Start
2.​ Define a function swap(int *a, int *b) that takes two integer pointers as parameters
3.​ Inside the function, swap the values using a temporary variable and pointers
4.​ Print the values before and after the swap function call in the main function
5.​ End
Code:

#include <stdio.h>

void swap(int *a, int *b) {


int temp;
printf("Before swapping in function: *a = %d, *b = %d\n", *a, *b);
temp = *a;
*a = *b;
*b = temp;
printf("After swapping in function: *a = %d, *b = %d\n", *a, *b);
}

int main() {
int a = 10, b = 20;

printf("Before function call: a = %d, b = %d\n", a, b);


swap(&a, &b);
printf("After function call: a = %d, b = %d\n", a, b);

return 0;
}

Post Lab Questions:

Question 1: Output of the C code

#include <stdio.h>
void fun(int *p, int *q)
{
*p = 20;
*q = *p * 2;
}
void main()
{
int i = 2, j = 10;
fun(&i, &j);
printf("%d %d", i, j);
}
Output: 20 40

Explanation:

1.​ Initially, i = 2 and j = 10


2.​ In the fun function:
○​ *p = 20 changes the value of i to 20
○​ *q = *p * 2 changes the value of j to 40 (which is 20 * 2)
3.​ The printf statement outputs the values of i and j, which are 20 and 40

Question 2: Output of the C code

#include <stdio.h>
void modify(int x)
{
x = x * 10;
}
void main()
{
int x = 10;
modify(x);
printf("%d", x);
}

Answer:

The output of this code is: 10

Explanation: This is an example of call by value. When modify(x) is called, a copy of x is


passed to the function. Any changes made to x inside the function only affect the local copy, not
the original variable in the main function. Therefore, the value of x in the main function remains
unchanged.

Question 3: Output of the C code

#include <stdio.h>
int fun(int *p, int q)
{
int temp;
temp = *p;
*p = q;
return temp;
}
void main()
{
int i = 10, j = 20;
j = fun(&i, j);
printf("%d %d", i, j);
}

Answer:

The output of this code is: 20 10

Explanation:

1.​ Initially, i = 10 and j = 20


2.​ In the call j = fun(&i, j):
○​ *p refers to i, so temp = *p sets temp = 10
○​ *p = q sets i = 20
○​ return temp returns the value 10
3.​ j is assigned the return value 10
4.​ Therefore, when printing, i = 20 and j = 10
Question (1): Program to add three numbers using call by value

#include <stdio.h>

// Function to add three numbers using call by value


int addThreeNumbers(int a, int b, int c) {
return a + b + c;
}

int main() {
int num1, num2, num3, sum;

// Input three numbers


printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

// Call the function and store the result


sum = addThreeNumbers(num1, num2, num3);

// Display the result


printf("Sum of %d, %d and %d is: %d\n", num1, num2, num3, sum);

return 0;
}

Question (2): Program to find area and perimeter of a rectangle using call by reference

#include <stdio.h>

// Function to calculate area and perimeter of a rectangle using call by reference


void calculateRectangle(float length, float width, float *area, float *perimeter) {
*area = length * width;
*perimeter = 2 * (length + width);
}

int main() {
float length, width, area, perimeter;

// Input length and width


printf("Enter the length of rectangle: ");
scanf("%f", &length);
printf("Enter the width of rectangle: ");
scanf("%f", &width);

// Call the function to calculate area and perimeter


calculateRectangle(length, width, &area, &perimeter);

// Display the results


printf("Area of the rectangle: %.2f square units\n", area);
printf("Perimeter of the rectangle: %.2f units\n", perimeter);

return 0;
}

Question (3): Find factorial of a number using call by value

#include <stdio.h>

// Function to calculate factorial using call by value


unsigned long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num;
unsigned long result;

// Input number
printf("Enter a non-negative integer: ");
scanf("%d", &num);

// Input validation
if (num < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
return 1;
}

// Calculate factorial
result = factorial(num);

// Display the result


printf("Factorial of %d = %lu\n", num, result);

return 0;
}
Experiment 12

Algorithm:

1.​ Start
2.​ Include necessary header files (stdio.h, math.h)
3.​ Define functions for each mathematical operation
4.​ In the main function, demonstrate the use of each function with examples
5.​ Print the results
6.​ End
Code:

#include <stdio.h>
#include <math.h>

int main() {
// Demonstration of mod (absolute value) operation
double a = -15.5;
double mod_result = (a < 0) ? -a : a;
printf("1. Mod operation: |%.1f| = %.1f\n", a, mod_result);

// Demonstration of square root operation


double b = 25;
double sqrt_result;
if (b < 0) {
printf("Error: Cannot calculate square root of a negative number.\n");
sqrt_result = -1;
} else {
sqrt_result = sqrt(b);
}
printf("2. Square root operation: sqrt(%.1f) = %.1f\n", b, sqrt_result);

// Demonstration of power operation


double c = 2, d = 3;
double power_result = pow(c, d);
printf("3. Power operation: %.1f^%.1f = %.1f\n", c, d, power_result);

// Demonstration of exponential operation


double e = 1;
double exp_result = exp(e);
printf("4. Exponential operation: e^%.1f = %.6f\n", e, exp_result);

// Demonstration of sum operation


double array[] = {1.5, 2.5, 3.5, 4.5, 5.5};
int n = sizeof(array) / sizeof(array[0]);
double sum_result = 0;
for (int i = 0; i < n; i++) {
sum_result += array[i];
}
printf("5. Sum operation: sum of array = %.1f\n", sum_result);

// Demonstration of round operation


double f = 7.6;
double round_result = round(f);
printf("6. Round operation: round(%.1f) = %.1f\n", f, round_result);
return 0;
}

(1) Uses of Functions:

1.​ Code Reusability: Functions allow us to write code once and use it multiple times,
reducing duplication.
2.​ Modularity: Functions help break down complex programs into smaller, manageable
modules.
3.​ Abstraction: Functions hide implementation details, allowing users to focus on what the
function does rather than how it does it.
4.​ Testing and Debugging: Functions make it easier to test and debug code as they can be
tested in isolation.
5.​ Readability: Functions with meaningful names make code more readable and
self-documenting.
6.​ Maintainability: Functions make code easier to maintain as changes need to be made in
only one place.
7.​ Encapsulation: Functions can encapsulate data processing logic, protecting data integrity.
8.​ Parameter Passing: Functions allow for flexible parameter passing using call by value or
call by reference.

(2) Four Math-Related In-Built Functions in C:

1.​ ceil(): Returns the smallest integer greater than or equal to a given number.
○​ Syntax: double ceil(double x)
○​ Example: ceil(3.2) returns 4.0
2.​ floor(): Returns the largest integer less than or equal to a given number.
○​ Syntax: double floor(double x)
○​ Example: floor(3.8) returns 3.0
3.​ fabs(): Returns the absolute value of a floating-point number.
○​ Syntax: double fabs(double x)
○​ Example: fabs(-5.6) returns 5.6
4.​ sin(): Returns the sine of an angle (in radians).
○​ Syntax: double sin(double x)
○​ Example: sin(0) returns 0.0

(3) Output of the C Program:

#include <stdio.h>
#include <math.h>
void main()
{
int i = 10;
printf("%d", log10(i));
}

The output of this program is: 1

Explanation: The log10() function returns the base-10 logarithm of a number. The base-10
logarithm of 10 is 1, as 10^1 = 10. However, log10() returns a double, but the printf statement
uses %d format specifier, which is for integers. This will truncate the decimal part, but in this
case, log10(10) = 1.0, so the output is 1.

(4) Program to Find Length Between Two Points:

#include <stdio.h>
#include <math.h>

// Function to calculate distance between two points


double distance(double x1, double y1, double x2, double y2) {
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
int main() {
double x1, y1, x2, y2, length;

// Get coordinates of the first point


printf("Enter coordinates of first point (x1 y1): ");
scanf("%lf %lf", &x1, &y1);

// Get coordinates of the second point


printf("Enter coordinates of second point (x2 y2): ");
scanf("%lf %lf", &x2, &y2);

// Calculate the distance


length = distance(x1, y1, x2, y2);

// Display the result


printf("Length of line joining points (%.2f, %.2f) and (%.2f, %.2f) is: %.2f units\n",
x1, y1, x2, y2, length);

return 0;
}

This distance calculator uses the Euclidean distance formula: len = √[(x₂ - x₁)² + (y₂ - y₁)²]

The program demonstrates the use of mathematical functions like sqrt() and pow() from
the math.h library to implement the distance formula correctly.

You might also like