Functions and recrusion.
1.Write a program using functions to find the average of three numbers.
2.Write a function to convert Celcius temperature into Fahrenheit.3.Write a function to calculate the force of attraction on a body of mass m exerted by earth. (g=9.8m/S2)
4.Write a program using recursion to calculate the nth element of the Fibonacci series.5.Write a recursive function to calculate the sum of first n natural numbers.
6.Write a program using functions to print the following pattern(first n lines):
#include<stdio.h>
float average (int a,int b,int c);
int main(){
int a,b,c;
printf("Enter the value of a");
scanf("%d", &a);
printf("Enter the value of b");
scanf("%d", &b);
printf("Enter the value of c");
scanf("%d", &c);
printf("The average is %f", average(a,b,c));
}
float average (int a,int b,int c){
float res;
res=(a+b+c)/3;
return res;
}
#include<stdio.h>
float far(float a);
int main(){
float a;
printf("Enter the Temparature in celsius:");
scanf("%f", &a);
printf("The temprature in Farenheit:%f", far(a));
}
float far(float a){
float b;
b=((a*9)/5)+32;
return b;
}
#include<stdio.h>
float force(float m);
int main(){
float m;
printf("Enter the Mass of the object:");
scanf("%f", &m);
printf("force of attraction is %fN.",
force(m));
}
float force(float m){
float a;
a=m*9.8;
return a;
}
4.Write a program using recursion to calculate the nth element of the Fibonacci series.
#include <stdio.h>
int fibonacci(int n) {
if (n <= 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
if (n < 0) {
printf("Invalid input. n should be a
non-negative integer.\n");
} else {
int result = fibonacci(n);
printf("The %dth element of the Fibonacci
series is: %d\n", n, result);
}
return 0;
}
#include <stdio.h>
int sumOfNaturals(int n) {
if (n <= 0) {
return 0; // Base case: Sum of 0 natural
` numbers is 0
} else {
return n + sumOfNaturals(n - 1);
// Recursive case: Sum of n naturals =
n + sum of (n-1) naturals
}
}
int main() {
int n;
printf("Enter a positive integer n: ");
scanf("%d", &n);
if (n < 0) {
printf("Invalid input. n should be
a positive integer.\n");
} else {
int result = sumOfNaturals(n);
printf("The sum of the first %d
natural numbers is: %d\n", n, result);
}
return 0;
}
*
***
*****
#include <stdio.h>
void printPattern(int n) { for (int i = 1; i <= n; i++) { // Print '*' for odd line numbers if (i % 2 == 1) { for (int j = 1; j <= i; j++) { printf("*"); } } // Print a new line after each line printf("\n"); }}int main() { int n; printf("Enter the number of lines: "); scanf("%d", &n); if (n < 1) { printf("Invalid input. Please enter a positive integer.\n"); } else { printPattern(n); } return 0;}
Comments
Post a Comment