Hello friends, this tutorial consists of 20 C programs for practice. These sample C programs cover the basics of C programming language. If you are looking to brush up your C coding skills, then these can give you a nice starting point.
Practice C Programming with 20 C Program Samples
Start learning and practicing C programming with our 20 sample programs. We covered 10 important areas of C programming and included 2 examples under each category. Let’s begin.
1. Getting Started with Basic Input and Output
Understanding the fundamentals of input and output is crucial in any programming language. In this section, we’ll start with simple programs to get user input, display output, and manipulate basic data types. Here are the two most basic C programs for quick practice.
Example 1: Hello, World!
#include <stdio.h>
#define GREETING "Hello, World!"
int main() {
printf("%s\n", GREETING);
return 0;
}
This classic “Hello, World!” program introduces you to the basic structure of a C program and the printf
function for output.
Example 2: User Input and Output
#include <stdio.h>
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
int nameLength = strlen(name);
if (nameLength > 10) {
printf("Wow, that's a long name!\n");
} else if (nameLength < 5) {
printf("Short and sweet!\n");
} else {
printf("Nice name length!\n");
}
return 0;
}
This program demonstrates taking user input and using it in the program, highlighting the use of the scanf
function.
2. Exploring Control Structures
Control structures are essential for building logic in your programs. This section will cover the use of conditionals (if, else) and loops (for, while) to control the flow of your C programs. Now, follow the below two C sample programs for practice.
Example 3: Checking Even or Odd
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
return 0;
}
This program utilizes an if-else
statement to determine whether the entered number is even or odd.
Example 4: Looping Through Numbers
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
Here, a simple for
loop is used to print numbers from 1 to 5, illustrating the concept of iteration.
3. Arrays and Strings
Arrays and strings are fundamental data structures in C. This section will guide you through creating, manipulating, and understanding these structures. The following are two C programs that you can practice and grasp the concept of arrays.
Example 5: Sum of Array Elements
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
int i;
for (i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum of array elements: %d\n", sum);
return 0;
}
In this program, we calculate the sum of elements in an array, demonstrating the use of arrays and a for
loop.
Example 6: String Manipulation
#include <stdio.h>
#include <string.h>
int main() {
char greeting[] = "Hello, ";
char name[] = "John";
char result[50];
strcpy(result, greeting);
strcat(result, name);
printf("%s\n", result);
return 0;
}
This program showcases string manipulation using the strcpy
and strcat
functions, emphasizing the importance of null-terminated strings.
4. Functions and Modular Programming
Functions help break down complex programs into smaller, manageable pieces. This section will explore creating and using functions for modular and efficient code.
Example 7: Function to Calculate Factorial
Let’s calculate the factorial of a given number using a recursive function.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int result = factorial(num);
printf("Factorial of %d is %d\n", num, result);
if (num > 0 && result % num == 0) {
printf("Interesting fact: %d is a factor of its factorial!\n", num);
}
return 0;
}
This program defines a recursive function to calculate the factorial of a number, demonstrating the use of functions in C. More than that it checks if the entered number is a factor of its factorial. If it is, it prints an additional interesting fact about the number and its factorial relationship.
Example 8: Modular Approach with Functions
Let’s calculate the square and cube of a given number.
#include <stdio.h>
int square(int num) {
return num * num;
}
int cube(int num) {
return num * num * num;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("\033[1;33m"); // Set text color to bright yellow
printf("Square: %d\n", square(number));
printf("Cube: %d\n", cube(number));
printf("\033[0m"); // Reset text color to default
if (number % 2 == 0) {
printf("\033[1;35m"); // Set text color to bright magenta
printf("Even numbers are cool!\n");
printf("\033[0m"); // Reset text color to default
} else {
printf("\033[1;36m"); // Set text color to bright cyan
printf("Odd numbers are unique!\n");
printf("\033[0m"); // Reset text color to default
}
return 0;
}
This program not only calculates the square and cube but also adds colorful output. Additionally, it provides a special message based on whether the input number is even or odd.
5. Pointers and Memory Usage in C Programs
Understanding pointers is crucial for efficient memory management in C. This section will delve into the concept of pointers and their application. Now, face some C sample programs to practice the concept of pointers.
Example 9: Basic Pointer Usage
This program demonstrates the basic concept of pointers by creating a pointer variable and assigning it the address of another variable.
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = 42;
int *ptr;
ptr = #
printf("Value of num: %d\n", *ptr);
int *dynamicNum;
dynamicNum = (int *)malloc(sizeof(int));
if (dynamicNum == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}
*dynamicNum = 42;
printf("Dynamically allocated num: %d\n", *dynamicNum);
free(dynamicNum); // Release the allocated memory
return 0;
}
This program introduces basic pointer usage, showcasing how to declare, assign, and dereference a pointer. It also dynamically allocates memory for an integer using a pointer and assigns value.
Example 10: Dynamic Memory Allocation
This program demonstrates dynamic memory allocation for an array, taking user input for the array size and elements.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size, i, sum = 0;
printf("Enter the size of the array: ");
scanf("%d", &size);
arr = (int *)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}
printf("Enter %d elements:\n", size);
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("You entered: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\nSum of the elements: %d\n", sum);
free(arr);
return 0;
}
This program demonstrates dynamic memory allocation using malloc
and free
, allowing the user to input an array of integers. Moreover, it also calculates and displays the sum of the entered elements.
6. File Handling in C
File handling is a crucial aspect of many applications. This section will guide you through reading from and writing to files in C. Here are a couple of sample C programs for practicing the File I/O concept.
Example 11: Writing to a File
The below code asks for the input and writes it to a file using file handling functions.
#include <stdio.h>
int main() {
FILE *file;
char data[100];
printf("Enter data to write to the file: ");
fgets(data, sizeof(data), stdin);
file = fopen("output.txt", "w");
if (file != NULL) {
fprintf(file, "%s", data);
fclose(file);
printf("Data written to file successfully.\n");
} else {
printf("Error opening the file.\n");
}
return 0;
}
This program opens a file in write mode and writes a string to it, showing basic file writing in C.
Example 12: Reading from a File
This c program reads a line of text from a file. It also checks for file existence and handles the case where the file might be empty:
#include <stdio.h>
int main() {
FILE *file;
char data[100];
file = fopen("input.txt", "r");
if (file != NULL) {
if (fscanf(file, "%[^\n]", data) == 1) {
fclose(file);
printf("Data read from file: %s\n", data);
} else {
printf("File is empty.\n");
fclose(file);
}
} else {
printf("Error opening the file.\n");
}
return 0;
}
This program checks if the file exists and reads data from it, illustrating basic file read operation in C.
7. Data Structures in C: Linked Lists
Linked lists are fundamental data structures in C. This section will guide you through creating, manipulating, and traversing single-linked lists. Here are some unique C sample programs to practice and learn the concept of a linked list.
Example 13: Creating and Displaying a Linked List
Let’s create a unique and situational example using a linked list structure to represent a playlist of songs, allowing users to add songs dynamically:
#include <stdio.h>
#include <stdlib.h>
struct Song {
char title[50];
char artist[50];
struct Song *next;
};
void displayPlaylist(struct Song *playlist) {
printf("Playlist:\n");
while (playlist != NULL) {
printf("%s by %s\n", playlist->title, playlist->artist);
playlist = playlist->next;
}
printf("End of Playlist\n");
}
void addSong(struct Song **playlist, const char *title, const char *artist) {
struct Song *newSong = (struct Song *)malloc(sizeof(struct Song));
snprintf(newSong->title, sizeof(newSong->title), "%s", title);
snprintf(newSong->artist, sizeof(newSong->artist), "%s", artist);
newSong->next = *playlist;
*playlist = newSong;
}
int main() {
struct Song *playlist = NULL;
char title[50];
char artist[50];
printf("Build your playlist (enter 'exit' to stop):\n");
while (1) {
printf("Enter song title: ");
scanf("%s", title);
if (strcmp(title, "exit") == 0) {
break;
}
printf("Enter artist: ");
scanf("%s", artist);
addSong(&playlist, title, artist);
}
displayPlaylist(playlist);
return 0;
}
In this example, users can dynamically build a playlist by entering song titles and artists. It demonstrates the creation and display of a simple singly linked list.
Example 14: Inserting at the Start of a Linked List
This program manages a to-do list. Users can dynamically add tasks to the beginning of the list, and we’ll display the to-do list after each addition:
#include <stdio.h>
#include <stdlib.h>
struct Task {
char description[100];
struct Task *next;
};
struct Task *addTask(struct Task *head, const char *description) {
struct Task *newTask = (struct Task *)malloc(sizeof(struct Task));
snprintf(newTask->description, sizeof(newTask->description), "%s", description);
newTask->next = head;
return newTask;
}
void displayToDoList(struct Task *head) {
printf("To-Do List:\n");
while (head != NULL) {
printf("- %s\n", head->description);
head = head->next;
}
printf("End of To-Do List\n");
}
int main() {
struct Task *toDoList = NULL;
char description[100];
printf("Build your to-do list (enter 'exit' to stop):\n");
while (1) {
printf("Enter task description: ");
scanf("%s", description);
if (strcmp(description, "exit") == 0) {
break;
}
toDoList = addTask(toDoList, description);
displayToDoList(toDoList);
}
return 0;
}
This program inserts nodes at the beginning of a linked list and displays the updated to-do list.
8. Bitwise Operations in C
Bitwise operations are essential for low-level programming tasks. This section will cover basic bitwise operations in C. Go through the below C programs and do some hands-on practice.
Example 15: Bitwise AND and OR Operations
#include <stdio.h>
// Simple bitwise AND operation
void simpleBitwiseAND() {
printf("---- Simple Bitwise AND ----\n");
int a = 12; // 1100 in binary
int b = 25; // 11001 in binary
int result = a & b;
printf("Result of bitwise AND: %d\n\n", result);
}
// Bitwise on permission flags
void complexBitwiseOps() {
printf("---- Managing Permissions ----\n");
// Define permission flags
#define READ_PERM 0b001
#define WRITE_PERM 0b010
#define EXECUTE_PERM 0b100
// User has read and write permissions
int userPerm = READ_PERM | WRITE_PERM;
// File requires read and execute permissions
int filePerm = READ_PERM | EXECUTE_PERM;
int result = userPerm & filePerm;
printf("User has permission to %s\n", (result == READ_PERM) ? "read" :
(result == WRITE_PERM) ? "write" :
(result == EXECUTE_PERM) ? "execute" : "perform the specified action");
}
int main() {
simpleBitwiseAND();
complexBitwiseOps();
return 0;
}
This program demonstrates the bitwise AND and OR operation between two integers.
Example 16: Bitwise And and OR to Select Options
Let’s create a scenario where a user can select options for a game using the bitwise OR operation:
#include <stdio.h>
void displayOptions(unsigned char options) {
printf("Selected options:\n");
printf("- Option A: %s\n", (options & 0b0001) ? "Enabled" : "Disabled");
printf("- Option B: %s\n", (options & 0b0010) ? "Enabled" : "Disabled");
printf("- Option C: %s\n", (options & 0b0100) ? "Enabled" : "Disabled");
printf("- Option D: %s\n", (options & 0b1000) ? "Enabled" : "Disabled");
}
int main() {
printf("---- Game Option Selection ----\n");
unsigned char userOptions = 0;
printf("Select options for the game (enter A to D, or 0 to finish):\n");
while (1) {
char selectedOption;
printf("Enter option letter (0 to finish): ");
scanf(" %c", &selectedOption);
if (selectedOption == '0') {
break;
}
switch (selectedOption) {
case 'A':
userOptions |= 0b0001;
break;
case 'B':
userOptions |= 0b0010;
break;
case 'C':
userOptions |= 0b0100;
break;
case 'D':
userOptions |= 0b1000;
break;
default:
printf("Invalid option. Please enter A to D.\n");
}
}
displayOptions(userOptions);
return 0;
}
This program illustrates the bitwise OR operation between two integers.
9. Enumerations in C Programs
Enumerations provide a way to create named integer constants, making code more readable. This section will cover the basics of enumerations in C.
Example 17: Basic Enumeration
#include <stdio.h>
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};
int main() {
enum Day today = WEDNESDAY;
printf("Today is %d\n", today);
return 0;
}
This program uses an enumeration to represent the days of the week.
Example 18: Enumeration with Values
#include <stdio.h>
enum Month {
JAN = 1,
FEB,
MAR,
APR,
MAY,
JUN,
JUL,
AUG,
SEP,
OCT,
NOV,
DEC
};
int main() {
enum Month currentMonth = MAR;
printf("Current month: %d\n", currentMonth);
return 0;
}
Here, the enumeration represents months with specific integer values.
10. Handle Errors in C Programs
Error handling is crucial for writing robust programs. This section will cover basic error-handling techniques using errno
and perror
. Check out the below two samples and practice with error handling in your c programs.
Example 19: Basic Error Handling with perror
This program demonstrates error handling when opening a file using fopen
.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define MAX_FILENAME_LEN 50
#define MAX_CONTENT_LEN 1000
int main() {
char filename[MAX_FILENAME_LEN];
FILE *file;
printf("Enter the name of the file to open: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL) {
perror("Error");
exit(EXIT_FAILURE);
}
printf("File contents:\n");
char content[MAX_CONTENT_LEN];
while (fgets(content, sizeof(content), file) != NULL) {
printf("%s", content);
}
fclose(file);
return 0;
}
The program asks users to enter the name of the file they want to open. It then attempts to open the specified file, displaying an error message if the file doesn’t exist.
Example 20: Checking for errno After System Call
The below program showcases error handling when opening a file using fopen
, specifically checking for the ENOENT
error.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define MAX_CONTENT_LENGTH 1000
int main() {
FILE *file = fopen("sample.txt", "r");
if (file == NULL) {
if (errno == ENOENT) {
printf("File not found. Do you want to create it? (y/n): ");
char response;
scanf(" %c", &response);
if (response == 'y' || response == 'Y') {
file = fopen("sample.txt", "w");
if (file == NULL) {
perror("Error creating file");
exit(EXIT_FAILURE);
}
printf("File created successfully. You can now add content.\n");
} else {
printf("Exiting without creating the file.\n");
exit(EXIT_SUCCESS);
}
} else {
perror("Error");
exit(EXIT_FAILURE);
}
} else {
printf("File contents:\n");
char content[MAX_CONTENT_LENGTH];
while (fgets(content, sizeof(content), file) != NULL) {
printf("%s", content);
}
fclose(file);
}
return 0;
}
The program checks for the file and prompts the user to create if it does not exist. If the user agrees, the program creates the file and informs the user that they can add content. However, on the contrary, the program exits gracefully. If the file exists, the program displays its contents.
The last few C programs covered data structures, bitwise operations, enumerations, and error handling. They provided you with a range of exercises to improve your C programming skills. Experiment with these examples and modify them. Create variations to deepen your understanding of C programming concepts.
Summary – 20 Programs for C Coding Practice
This tutorial has provided a comprehensive set of C programming exercises covering fundamental concepts such as input/output, control structures, arrays, functions, pointers, memory management, and file handling. By working through these examples, you’ll not only reinforce your understanding of C but also gain practical experience that is invaluable for real-world programming tasks. Remember to experiment with variations of these programs and explore additional challenges to further enhance your C programming skills.
Happy coding!