Introduction
Built-in functions in C are predefined functions provided by the C standard library. These functions perform common tasks and are ready to use without requiring the programmer to write them from scratch. They are included through header files and cover areas like input/output, string manipulation, mathematical operations, memory management, and more.
Key Concepts
Standard Library: Collection of built-in functions provided by C Header Files: Files containing function declarations and definitions Function Prototype: Declaration that specifies function signature Library Linking: Process of connecting library functions to your program
Input/Output Functions (stdio.h)
Basic I/O Functions
#include <stdio.h>
int main() {
char name[50];
int age;
float height;
// Output functions
printf("Enter your details:\n");
printf("Name: ");
// Input functions
scanf("%s", name);
printf("Age: ");
scanf("%d", &age);
printf("Height (in meters): ");
scanf("%f", &height);
// Formatted output
printf("\nYour Details:\n");
printf("Name: %s\n", name);
printf("Age: %d years\n", age);
printf("Height: %.2f meters\n", height);
return 0;
}
Character I/O Functions
#include <stdio.h>
int main() {
char ch;
printf("Enter characters (press 'q' to quit):\n");
while (1) {
ch = getchar(); // Read single character
if (ch == 'q') {
break;
}
printf("You entered: ");
putchar(ch); // Print single character
printf("\n");
}
return 0;
}
String I/O Functions
#include <stdio.h>
int main() {
char sentence[100];
printf("Enter a sentence: ");
gets(sentence); // Read entire line (deprecated, use fgets instead)
printf("You entered: ");
puts(sentence); // Print string with newline
// Safer alternative using fgets
printf("Enter another sentence: ");
fgets(sentence, sizeof(sentence), stdin);
printf("You entered: %s", sentence);
return 0;
}
String Functions (string.h)
String Length and Copying
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello World";
char destination[50];
char append_str[] = " - Welcome!";
// String length
int length = strlen(source);
printf("Length of '%s': %d\n", source, length);
// String copy
strcpy(destination, source);
printf("Copied string: %s\n", destination);
// String concatenation
strcat(destination, append_str);
printf("After concatenation: %s\n", destination);
return 0;
}
String Comparison and Search
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
char str3[] = "apple";
char search_str[] = "Hello World Programming";
char *ptr;
// String comparison
int result1 = strcmp(str1, str2);
int result2 = strcmp(str1, str3);
printf("Comparing '%s' and '%s': %d\n", str1, str2, result1);
printf("Comparing '%s' and '%s': %d\n", str1, str3, result2);
// String search
ptr = strstr(search_str, "World");
if (ptr != NULL) {
printf("'World' found at position: %ld\n", ptr - search_str);
}
// Character search
ptr = strchr(search_str, 'o');
if (ptr != NULL) {
printf("First 'o' found at position: %ld\n", ptr - search_str);
}
return 0;
}
Advanced String Functions
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "apple,banana,orange,grape";
char copy_str[50];
char *token;
// Safe string copy with size limit
strncpy(copy_str, str, sizeof(copy_str) - 1);
copy_str[sizeof(copy_str) - 1] = '\0';
printf("Original: %s\n", str);
printf("Copy: %s\n", copy_str);
// String tokenization
printf("\nTokens:\n");
token = strtok(copy_str, ",");
while (token != NULL) {
printf("- %s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
Mathematical Functions (math.h)
Basic Mathematical Operations
#include <stdio.h>
#include <math.h>
int main() {
double x = 16.0, y = 3.0, z = -5.5;
// Power and square root
printf("%.2f raised to power %.2f = %.2f\n", x, y, pow(x, y));
printf("Square root of %.2f = %.2f\n", x, sqrt(x));
// Absolute values
printf("Absolute value of %.2f = %.2f\n", z, fabs(z));
// Ceiling and floor
printf("Ceiling of %.2f = %.2f\n", z, ceil(z));
printf("Floor of %.2f = %.2f\n", z, floor(z));
// Logarithmic functions
printf("Natural log of %.2f = %.2f\n", x, log(x));
printf("Base-10 log of %.2f = %.2f\n", x, log10(x));
return 0;
}
Trigonometric Functions
#include <stdio.h>
#include <math.h>
#define PI 3.14159265359
int main() {
double angle_degrees = 45.0;
double angle_radians = angle_degrees * PI / 180.0;
printf("Angle: %.2f degrees (%.4f radians)\n", angle_degrees, angle_radians);
// Trigonometric functions
printf("sin(%.2f°) = %.4f\n", angle_degrees, sin(angle_radians));
printf("cos(%.2f°) = %.4f\n", angle_degrees, cos(angle_radians));
printf("tan(%.2f°) = %.4f\n", angle_degrees, tan(angle_radians));
// Inverse trigonometric functions
double value = 0.5;
printf("\nasin(%.2f) = %.2f degrees\n", value, asin(value) * 180.0 / PI);
printf("acos(%.2f) = %.2f degrees\n", value, acos(value) * 180.0 / PI);
printf("atan(%.2f) = %.2f degrees\n", value, atan(value) * 180.0 / PI);
return 0;
}
Memory Management Functions (stdlib.h)
Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int size = 5;
// Allocate memory
numbers = (int*)malloc(size * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Initialize and display
printf("Enter %d numbers:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &numbers[i]);
}
printf("Numbers entered: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Reallocate for more numbers
size = 8;
numbers = (int*)realloc(numbers, size * sizeof(int));
if (numbers == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}
printf("Memory reallocated for %d numbers\n", size);
// Free memory
free(numbers);
printf("Memory freed\n");
return 0;
}
Utility Functions
#include <stdio.h>
#include <stdlib.h>
int main() {
char str_number[] = "12345";
char str_float[] = "123.45";
// String to number conversion
int number = atoi(str_number);
float decimal = atof(str_float);
printf("String '%s' to integer: %d\n", str_number, number);
printf("String '%s' to float: %.2f\n", str_float, decimal);
// Random number generation
printf("\nRandom numbers:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", rand() % 100); // Random number 0-99
}
printf("\n");
// Absolute value
int negative = -42;
printf("Absolute value of %d = %d\n", negative, abs(negative));
return 0;
}
Character Classification Functions (ctype.h)
Character Testing Functions
#include <stdio.h>
#include <ctype.h>
int main() {
char test_chars[] = {'A', 'z', '5', '$', ' ', '\n'};
int size = sizeof(test_chars) / sizeof(test_chars[0]);
printf("Character Analysis:\n");
printf("Char\tAlpha\tDigit\tUpper\tLower\tSpace\tPunct\n");
printf("----\t-----\t-----\t-----\t-----\t-----\t-----\n");
for (int i = 0; i < size; i++) {
char ch = test_chars[i];
printf("'%c'\t%d\t%d\t%d\t%d\t%d\t%d\n",
(ch == '\n') ? 'n' : ch,
isalpha(ch),
isdigit(ch),
isupper(ch),
islower(ch),
isspace(ch),
ispunct(ch));
}
return 0;
}
Character Conversion Functions
#include <stdio.h>
#include <ctype.h>
int main() {
char sentence[] = "Hello World 123!";
char converted[100];
int i;
printf("Original: %s\n", sentence);
// Convert to uppercase
for (i = 0; sentence[i] != '\0'; i++) {
converted[i] = toupper(sentence[i]);
}
converted[i] = '\0';
printf("Uppercase: %s\n", converted);
// Convert to lowercase
for (i = 0; sentence[i] != '\0'; i++) {
converted[i] = tolower(sentence[i]);
}
converted[i] = '\0';
printf("Lowercase: %s\n", converted);
return 0;
}
Time Functions (time.h)
Basic Time Operations
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
struct tm *time_info;
char time_string[100];
// Get current time
time(¤t_time);
printf("Current timestamp: %ld\n", current_time);
// Convert to readable format
time_info = localtime(¤t_time);
printf("Current time: %s", asctime(time_info));
// Custom formatted time
strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
printf("Formatted time: %s\n", time_string);
// Individual components
printf("Year: %d\n", time_info->tm_year + 1900);
printf("Month: %d\n", time_info->tm_mon + 1);
printf("Day: %d\n", time_info->tm_mday);
printf("Hour: %d\n", time_info->tm_hour);
printf("Minute: %d\n", time_info->tm_min);
printf("Second: %d\n", time_info->tm_sec);
return 0;
}
Practical Examples
Text Processing Program
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void analyzeText(char text[]) {
int length = strlen(text);
int words = 0, vowels = 0, consonants = 0, digits = 0;
printf("Text Analysis for: \"%s\"\n", text);
printf("Length: %d characters\n", length);
for (int i = 0; i < length; i++) {
char ch = tolower(text[i]);
if (isalpha(ch)) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
} else if (isdigit(ch)) {
digits++;
} else if (isspace(ch)) {
words++;
}
}
words++; // Add 1 for the last word
printf("Words: %d\n", words);
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
printf("Digits: %d\n", digits);
}
int main() {
char text[200];
printf("Enter a sentence: ");
fgets(text, sizeof(text), stdin);
// Remove newline if present
if (text[strlen(text) - 1] == '\n') {
text[strlen(text) - 1] = '\0';
}
analyzeText(text);
return 0;
}
Calculator Program Using Built-in Functions
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void displayMenu() {
printf("\n=== Scientific Calculator ===\n");
printf("1. Basic Operations (+, -, *, /)\n");
printf("2. Power and Square Root\n");
printf("3. Trigonometric Functions\n");
printf("4. Logarithmic Functions\n");
printf("5. Exit\n");
printf("Choose an option: ");
}
int main() {
int choice;
double num1, num2, result;
while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);
if (num2 != 0) {
printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
} else {
printf("Division by zero error!\n");
}
break;
case 2:
printf("Enter number: ");
scanf("%lf", &num1);
printf("Square root of %.2f = %.2f\n", num1, sqrt(num1));
printf("Enter base and exponent: ");
scanf("%lf %lf", &num1, &num2);
printf("%.2f ^ %.2f = %.2f\n", num1, num2, pow(num1, num2));
break;
case 3:
printf("Enter angle in degrees: ");
scanf("%lf", &num1);
num1 = num1 * M_PI / 180.0; // Convert to radians
printf("sin = %.4f\n", sin(num1));
printf("cos = %.4f\n", cos(num1));
printf("tan = %.4f\n", tan(num1));
break;
case 4:
printf("Enter number: ");
scanf("%lf", &num1);
if (num1 > 0) {
printf("Natural log = %.4f\n", log(num1));
printf("Base-10 log = %.4f\n", log10(num1));
} else {
printf("Logarithm undefined for non-positive numbers!\n");
}
break;
case 5:
printf("Thank you for using the calculator!\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Common Built-in Functions Summary
| Category | Header | Common Functions |
|---|---|---|
| I/O | stdio.h | printf, scanf, getchar, putchar, gets, puts |
| String | string.h | strlen, strcpy, strcat, strcmp, strstr, strtok |
| Math | math.h | pow, sqrt, sin, cos, tan, log, exp, ceil, floor |
| Memory | stdlib.h | malloc, calloc, realloc, free, exit |
| Character | ctype.h | isalpha, isdigit, toupper, tolower, isspace |
| Time | time.h | time, localtime, asctime, strftime |
Best Practices
- Always include proper headers for the functions you use
- Check return values for functions that can fail (like malloc)
- Use appropriate data types for function parameters
- Free allocated memory to prevent memory leaks
- Validate input before passing to functions
- Use const parameters when functions shouldn’t modify data
Summary
Built-in functions in C provide powerful, tested, and optimized solutions for common programming tasks. They save development time and reduce errors by providing standard implementations for I/O operations, string manipulation, mathematical calculations, memory management, and more. Understanding and effectively using these functions is essential for efficient C programming.
Part of BCA Programming with C Course (UGCOA22J201)