Week 6
Week 6
● Functions
● standard library functions
● math library functions
● Random number generation
● Programmer defined functions
● Calling functions by value
● Scope rules (global and local variables)
// Global variables
int birthYear, birthMonth, birthDay;
int currentYear, currentMonth, currentDay;
int daysInYear = 360; // Assuming a year has 360 days
return ageInDays;
}
int main() {
readInput(); // Call the function to read input
int ageInDays = computeAgeInDays(); // Compute the age in days
printf("Your age in days is: %d\n", ageInDays);
return 0;
}
Q1 :Here's a simple example in C that uses the math library functions ceil, floor, pow, sqrt, and
abs to perform various mathematical operations:
#include <stdio.h>
#include <math.h>
int main() {
double x = 4.5;
double y = -7.8;
return 0;
}
Q2: You can define your own functions that make use of the math library functions
to perform specific calculations. Here's an example of a user-defined function that
uses math library functions to calculate the distance between two points in 2D
space:
#include <stdio.h>
#include <math.h>
return distance;
}
int main() {
double x1 = 1.0, y1 = 2.0;
double x2 = 4.0, y2 = 6.0;
Q3: your turn :Write a C function that calculates and returns the area of a circle
using the math library's pow and M_PI (which represents the value of π). The
formula for the area of a circle is A = π * r^2, where "r" is the radius of the circle
int main() {
double radius = 5.0; // Change the radius as needed
return 0;
}
Q4: C program with a function called generateRand that takes a start and end
value, generates a random number within that range, and then prints the result in
the main function:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Seed the random number generator with the current time
srand(time(NULL));
return 0;
}
int main() {
double side1, side2;
printf("Enter the lengths of the two sides: ");
scanf("%lf %lf", &side1, &side2);
return 0;
}