C programming exercises are a great way to help you improve your problem-solving skills. Are you looking for some coding exercise questions? Let us review them in this article!
Your journey to learn a programming language gets steady when you practice writing code in that language. The C programming language is one of the fundamental languages that requires a solid practice of coding concepts.
It has many versatile concepts where students get stuck due to a lack of understanding of the subject knowledge and they look forย C Programming help.ย
In this article, we will see how we can solve programs in C and implement the coding solutions for all the concepts that you have learned in this programming language.
Are you ready to explore C programming exercises? Let us dive in then!
Summary Of The Article:
The C programming language is a low-level yet powerful programming language that offers diverse applications to us.
C exercises for beginners include its basics like datatypes, syntax, and functions.
The more you solve C programming exercises, the better you become in the C language.
For beginners or novice programmers, C exercises are a beneficial learning resource that can help them develop logic-building skills and solve real-world problems using the C language.
12 Helpful C Programming Exercises For Beginners
Let us finally start to explore C exercises that you can try to solve as a beginner. C language is vast and offers us a lot of concepts that we can use. We would be able to understand these concepts in a better way, once we know how to implement them.
So, without any delay, let me take you further into the agenda for today. Let’s look at the C exercises and programming examples. Keep reading!
Basic C Programming Exercises For Beginners
In this subsection, I will tell you about some basic C exercises that will help you strengthen your foundational knowledge of the C language. We will study these with the help of programming examples and code. So, let us find out what these are!
1. Write a C program to check if a triangle is a right-angle triangle.
We know, we can prove that a triangle is right-angled if the sum of the squares of two sides is equal to the square of the third side. This is commonly known as the Pythagorean Theorem. We will use this concept to solve this problem. The C code is given below.
#include
int RightTriangle(int s1, int s2, int s3) {
// Arrange sides in ascending order
if (s1 > s2) {
int temp = s1;
s1 = s2;
s2 = temp;
}
if (s2 > s3) {
int temp = s2;
s2 = s3;
s3 = temp;
}
// Check right triangle using pythagorean theorem
if (s1 * s1 + s2 * s2 == s3 * s3)
return 1;
else
return 0;
}
int main() {
int s1, s2, s3;
// Input the sides of the triangle
printf("Enter the first side of the triangle: ");
scanf("%d", &s1);
printf("Enter the second side of the triangle: ");
scanf("%d", &s2);
printf("Enter the third side of the triangle: ");
scanf("%d", &s3);
// calling the function
if (RightTriangle(s1, s2, s3))
printf("It is a right-angled triangle.\n");
else
printf("It isn't a right-angled triangle.\n");
return 0;
}
In this code, we are using a function to arrange the sides of a triangle and then we are checking if the triangle is right-angled. If it is, our function returns 1, else, it returns 0.
If itโs not written well, it might flag anย error in the C programming project.
Let us see the output of the code with an example of input values.
Output:
2. Write a C program to convert a decimal number to its octal equivalent
Decimal numbers have a base 10, while octal has a base 8. To convert decimal to octal, we will have to continuously divide the number by 8 until we get 0 as the remainder. Let us see how to write the code for it.
#include
void decimalToOctal(int n) {
int octalNumber[100], i = 0;
while (n != 0) {
octalNumber[i] = n % 8;
n /= 8;
i++;
}
printf("Octal equivalent: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", octalNumber[j]);
}
printf("\n");
}
int main() {
int n;
// Input number
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("Octal equivalent is: ");
decimalToOctal(n);
}
In this code, we are taking a decimal value as an input and passing it as an argument to the function decimalToOctal() where we are using the while loop to divide it continuously. After we get our octal number, we return it to the main function.
Output:
3. Write a C program to swap two numbers using Macro
A macro, in C language, is a code snippet or a piece of code defined using #define that is replaced with some value. For example, #define PI 3.14 will set the value of “PI” to 3.14. Let us see a code for how can we swap two numbers using a macro.
#include
// define the SWAP function as a macro
// here we are also using XOR operator
#define SWAP(a, b) { (a) ^= (b); (b) ^= (a); (a) ^= (b); }
int main() {
int n1, n2;
// Input two numbers
printf("Enter two numbers: ");
scanf("%d %d", &n1, &n2);
// numbers before swapping
printf("Before swapping: n1 = %d, n2 = %d\n", n1, n2);
// calling macro for swapping
SWAP(n1, n2);
// numbers after swapping
printf("After swapping: n1 = %d, n2 = %d\n", n1, n2);
return 0;
}
Here, SWAP() is defined as a macro that helps us perform our operation. The function has used the XOR operation three times to correctly swap the values of the input.
Output:
Array and String C Exercises For Beginners
In C programming, arrays and strings are the two datatypes that are extremely crucial. Many coding interviewers ask questions related to array or string manipulation. Let’s see some C programming examples for it!
4. Write a C program to concatenate two strings.
This is one of the common C exercises for string manipulation. Concatenation is the process of joining strings together. Let us see how to do it in the C program below.
#include
#include
int main() {
char str1[] = "Coding"; // First string
char str2[]= "Zap"; // Second string
// Concatenate the strings
strcat(str1, str2);
// Print the concatenated string
printf("Concatenated string: %s\n", str1);
return 0;
}
In this C program, we have used two example strings, the first given string is “Coding” and the second one is “Zap.” To concatenate these strings, we are using the strcat() function, that is one of the pre-defined functions in the <string.h> library. It will add str2 value to str1 and then we will print it.
Output:
5. Write a C program to sort array elements in descending order using bubble sort.
Bubble sorting is one of the simplest sorting algorithms that we can use on arrays. Here, we check the first element with the second element and then swap them if the first one is greater than the next one. Since we have to display the array in decreasing order, we will swap if the previous element is smaller.
#include
// Bubble sort function
void bubbleSortDesc(int arr[], int n) {
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
// n is the size of the array
printf("Enter size of the array: ");
scanf("%d", &n);
int arr[n];
// Input elements using for loop
printf("Enter %d elements of the array: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// call function
bubbleSortDesc(arr, n);
// Print the sorted array using for loop
printf("Sorted array in descending order: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
In this program, we have used the C language functions to perform sorting in decreasing order. This is one of the basic C exercises that can be used in various projects as well. Have a look at its result below.
Output:
6. Write a C program to calculate the average of all elements in an array
Mean or averages are also one of the basic concepts that we can implement. Have a look at the program written in C language to get the solution for solving it.
#include
// Function to calculate the average
float calculateAverage(int arr[], int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum / n;
}
int main() {
int n; //size of the array
printf("Enter the size of the array: ");
scanf("%d", &n);
// Declare an array of the given size
int arr[n];
// Input values
printf("Enter %d elements of the array: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// call function
float avg = calculateAverage(arr, n);
// Print the average
printf("The average of elements is: %.2f\n", avg);
return 0;
}
As you can see, most of the C programming examples use functions. Why is that so? Well, they are a great way to make your C language program reusable. Here also, we have made a program to calculate the mean of values of an array.
Output:
7. Write a C program to find the minimum and maximum element in an array
Let’s move forward to see our next C language program in our list of C programming examples. Here, we need to find the max and min values in an array. For simplicity, we will be using positive integer values only.
#include
// Function to find the maximum element
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Function to find the minimum element
int findMin(int arr[], int size) {
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid input\n");
return 1;
}
int arr[n]; // declaring array
// Input values
printf("Enter %d elements of the array: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// calling functions
int max = findMax(arr, n);
int min = findMin(arr, n);
// Print results
printf("Maximum element in the array: %d\n", max);
printf("Minimum element in the array: %d\n", min);
return 0;
}
Our first step in this program will be to define functions to find the minimum and maximum values where we will use a for loop to iterate over the array and find out the largest and smallest element.
Output:
Numerical And Mathematical C Exercises For Beginners
Beginners can learn C programming exercises for arithmetic or numerical operations. One of the basic programs is to create a simple calculator. Here, I will tell you about more such C programming examples and basic mathematical exercise questions that you can practice.
8. Write a C program to find the factorial of a number using recursion
In this exercise, we will see the answer to how to find the factorial of a number. But, we will make use of the recursion concept in our program. Let’s see a basic program to see how recursive functions work.
#include
// recursive function
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);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
return 1;
}
int fact = factorial(num);
printf("Factorial is: %d\n", fact);
return 0;
}
So, in the above code statements, we have made a recursive function factorial(). This function runs until it satisfies the terminating expressions. Once we reach that line, the function stops the execution.
Output:
9. Write a C program to print the Fibonacci series
A Fibonacci series is a special sequence where the value of a term is equal to the sum of its previous terms. The series starts with 0 and goes like 0,1,1,2,3,5….so on. Let us see how to implement the answer for it.
#include
// Function to print Fibonacci series up to n terms
void fibonacci(int n) {
int prev = 0, current = 1, next;
printf("Fibonacci series up to %d terms: ", n);
printf("%d %d ", prev, current);
for (int i = 3; i <= n; i++) {
next = prev + current;
printf("%d ", next);
prev = current;
current = next;
}
printf("\n");
}
int main() {
int n; // number of terms
printf("Enter the number of terms for Fibonacci series: ");
scanf("%d", &n);
// Check if the number of terms is valid
if (n <= 0) {
printf("Invalid input\n");
return 1;
}
int first = 0, second = 1, third;
printf("Fibonacci series: ");
printf("%d %d ", first, second);
for (int i = 3; i <= n; i++) {
third = first + second;
printf("%d ", third);
first = second;
second = third;
}
printf("\n");
return 0;
}
In this code, we have initialized the variable ‘first’ and the variable ‘second’ to the starting terms. Then, using a for loop, we will print the series up to the terms the user has input. Can you think of other solutions to this problem? One answer can be by using functions.
Output:
If youโre interested to know about the methods to implement Fibonacci series in C, then you can check out our article.
10. Write a C program to check whether a given number is Armstrong
Next in the list of C programming exercises is the program to check if a number is armstrong number. These are those numbers where the sum of the digits to the power of the number of digits is equal to the number itself. Let us see the C programming answer for it.
#include
#include
// Function to calculate the number of digits in a number
int countDigits(int num) {
int count = 0;
while (num != 0) {
num /= 10;
count++;
}
return count;
}
// Function to check whether a number is an Armstrong number or not
int isArmstrong(int num) {
int originalNum, remainder, result = 0, n = 0;
// Store the number of digits in num
n = countDigits(num);
originalNum = num;
// Calculate the sum of nth power of each digit
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
// Check if the result is equal to the original number
if (result == num)
return 1; // Armstrong number
else
return 0; // Not an Armstrong number
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int count = 0;
while (num != 0) {
num /= 10;
count++;
}
int original, remainder, result = 0, n = 0;
original = num;
n = count;
// Calculate the sum of nth power of each digit
while (original != 0) {
remainder = original % 10;
result += pow(remainder, n);
original /= 10;
}
// Check if the result is equal to the original number
if (result == num)
printf("Armstrong Number");
else
printf("Not an Armstrong number");
return 0;
}
The user will first provide an input number to us and we will call functions to count the digits and calculate the sum of the powered digits. If our statements are correct, a message stating that the number is an Armstrong will be printed.
Output:
Advanced Concepts in C exercises with programming examples
I hope that by now you have grasped and understood the exercises in C programming. Do you wish to take it to the next level? Let us see some C programming exercises that utilizes the more difficult and deep concepts of the language.
11. Write a C program to create a dynamic array
We have seen how arrays are declared in the previous solutions. Now, let us create them using dynamic memory allocation. Look at the C programming example below to understand.
#include
#include
int main() {
int size;
// Input the size of the dynamic array
printf("Enter the size of the dynamic array: ");
scanf("%d", &size);
// Allocate memory for the dynamic array
int *dynamicArray = (int *)malloc(size * sizeof(int));
// Check if memory allocation is successful
if (dynamicArray == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Enter input value
printf("Enter element value of the dynamic array: ", size);
for (int i = 0; i < size; i++) {
scanf("%d", &dynamicArray[i]);
}
// Print value
printf("Dynamic array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", dynamicArray[i]);
}
printf("\n");
// Free the memory using free()
free(dynamicArray);
return 0;
}
In this program answer, we have used the malloc() and free() functions provided by the C programming library. Malloc() assigns memory to the array, whereas, free() terminates or drops it as the program execution ends.
Output:
12. Write a C program to copy one file’s contents to another
I/O handling or file handling in C programming is also a vital concept that is used in many C programming projects. Let’s see a small example of how can we copy one file’s contents to another.
#include
#include
int main() {
FILE *sourceFile, *destinationFile;
char sourceFileName[100], destinationFileName[100];
char ch;
// Input the source file name
printf("Enter the name of the source file: ");
scanf("%s", sourceFileName);
// Open the source file in read mode
sourceFile = fopen(sourceFileName, "r");
// Check if the source file exists
if (sourceFile == NULL) {
printf("Error opening source file.\n");
exit(1);
}
// Input the destination file name
printf("Enter the name of the destination file: ");
scanf("%s", destinationFileName);
// Open the destination file in write mode
destinationFile = fopen(destinationFileName, "w");
// Check if the destination file exists
if (destinationFile == NULL) {
printf("Error opening destination file.\n");
fclose(sourceFile);
exit(1);
}
// Copy content from source file to destination file
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}
// Close files
fclose(sourceFile);
fclose(destinationFile);
printf("File copied successfully.\n");
return 0;
}
Here, we will have to specify the path of the source file as well as the destination file first. Ensure that you mention the correct file path. We will then make functions to display an error message incase we are unable to perform the operation.
To copy the contents, we will use a while loop and the fgetc() function to get the characters one by one and put them in the destination file. Make sure that after performing the operation, you close the files otherwise the progress will not be saved.
Output:
Conclusion:
So now you know some important and beginner-friendly C programming exercises. From fundamentals like datatypes, characters, expressions, to complex concepts like DMA and data structures, C programming covers everything!
So, what’s the wait for? Open your code editors and start solving! Happy coding!
Takeaways:
The programming world is an ever-evolving world and there is a constant need to study the crucial and foundational concepts.
Practice to write code in C to fully understand the language and make your journey smooth.
From user inputs to I/O handling, each concept can have various solutions. Try to write the most optimized answer to get better at C programming.