0% found this document useful (0 votes)
1 views3 pages

C Function Examples Part2

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)
1 views3 pages

C Function Examples Part2

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/ 3

Basic C Functions with Examples (Part 2)

11. isEven() - Check if number is even


#include <stdio.h>
int isEven(int a) {
return a % 2 == 0;
}
void main() {
int x = 4;
if(isEven(x))
printf("%d is Even", x);
else
printf("%d is Odd", x);
}

12. isOdd() - Check if number is odd


#include <stdio.h>
int isOdd(int a) {
return a % 2 != 0;
}
void main() {
int x = 7;
if(isOdd(x))
printf("%d is Odd", x);
else
printf("%d is Even", x);
}

13. isPrime() - Check if number is prime


#include <stdio.h>
int isPrime(int n) {
if(n <= 1) return 0;
for(int i = 2; i < n; i++) {
if(n % i == 0)
return 0;
}
return 1;
}
void main() {
int x = 7;
if(isPrime(x))
printf("%d is Prime", x);
else
printf("%d is Not Prime", x);
}

14. sumDigits() - Sum of digits of a number


#include <stdio.h>
int sumDigits(int n) {
int sum = 0;
while(n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
void main() {
int x = 1234;
printf("Sum of digits = %d", sumDigits(x));
}

15. reverse() - Reverse a number


#include <stdio.h>
int reverse(int n) {
int rev = 0;
while(n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
void main() {
int x = 123;
printf("Reverse = %d", reverse(x));
}

16. swap() - Swap two numbers


#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void main() {
int x = 5, y = 10;
swap(&x, &y);
printf("x = %d, y = %d", x, y);
}

17. power() - Calculate a^b


#include <stdio.h>
int power(int a, int b) {
int result = 1;
for(int i = 1; i <= b; i++)
result *= a;
return result;
}
void main() {
int x = 2, y = 3;
printf("%d^%d = %d", x, y, power(x, y));
}
18. table() - Print multiplication table
#include <stdio.h>
void table(int n) {
for(int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", n, i, n*i);
}
}
void main() {
int x = 5;
table(x);
}

19. fibonacci() - Print Fibonacci series


#include <stdio.h>
void fibonacci(int n) {
int a = 0, b = 1, c;
printf("%d %d ", a, b);
for(int i = 3; i <= n; i++) {
c = a + b;
printf("%d ", c);
a = b;
b = c;
}
}
void main() {
int terms = 10;
fibonacci(terms);
}

20. gcd() - Greatest common divisor


#include <stdio.h>
int gcd(int a, int b) {
while(b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
void main() {
int x = 48, y = 18;
printf("GCD = %d", gcd(x, y));
}

You might also like