In this blogging you know about digital world.
- Get link
- X
- Other Apps
20 Simple C Programs for Beginners
20 Simple C Programs for
Beginners

About C Programming
Language
C is a general-purpose programming language that was developed in the
early 1970s at Bell Labs by Dennis Ritchie. It is one of the most widely used
and influential programming languages in the history of computing. Here are
some key features and aspects of the C programming language:
1. Procedural
Language: C is a procedural programming language, which means that it focuses
on writing functions or procedures that operate on data. It follows a top-down
approach to problem-solving.
2. Low-Level
Language: C is often referred to as a "high-level assembly language"
because it provides low-level memory manipulation features. This allows for
efficient control over hardware and memory, making it suitable for systems
programming and embedded systems development.
3. Portable: C
programs can be compiled and run on a wide variety of platforms, making it a
portable language. This portability is achieved through the use of a compiler,
which translates C code into machine-specific binary code.
4. Efficient: C
is known for its efficiency and performance. It allows for direct memory
manipulation and provides fine-grained control over system resources, making it
well-suited for tasks where speed and resource utilization are critical.
5. Structured
Programming: C supports structured programming concepts such as loops,
conditionals, and functions, which aid in writing clear and maintainable code.
6. Extensible:
C allows the creation of libraries and reusable code modules, which promotes
code reusability and extensibility. This feature has led to the development of
numerous libraries and frameworks in various domains.
7.
Standardized: The C programming language has a standardized version known as
the ANSI C or ISO C standard. This standardization ensures consistency across
different implementations and compilers.
8. Large
Community and Ecosystem: C has a large and active community of developers. It
has been used in the development of operating systems (like Unix and Linux),
embedded systems, game engines, and many other applications.
9. Pointers: C
is well-known for its use of pointers, which are variables that store memory
addresses. Pointers provide powerful memory manipulation capabilities but can
also lead to programming errors if not used carefully.
10. Static
Typing: C is a statically typed language, which means that variable types are
determined at compile time. This helps catch type-related errors before the
program runs.
11. No Built-in
Object-Oriented Features: C does not have built-in support for object-oriented
programming (OOP) concepts like classes and objects. However, developers can
implement OOP principles using C's features, such as structures and function
pointers.
12.
Pre-processor Directives: C uses pre-processor directives (e.g., #include and
#define) to manipulate the code before compilation. This enables conditional
compilation, macro definitions, and file inclusion.
13. Standard
Library: C comes with a standard library that provides functions for common
tasks like input/output, string manipulation, and memory management.
C has had a
profound influence on the development of other programming languages, including
C++, C#, and Objective-C, among others. Its simplicity, efficiency, and
portability continue to make it a valuable tool for a wide range of software
development tasks. However, it's worth noting that while C offers great power
and control, it also requires careful attention to detail and can be more
error-prone compared to higher-level languages.
List of Basic C
Programs.
1. Calculate the Percentage of 5 Subjects
It is simple to calculate the percentage of five subjects, all
you need to do is add all of the marks and multiply that total by 100. Then
divide that by the total number of marks a student is permitted to receive. You
will ultimately receive the results as a percentage of the 5 subjects.
#include <stdio.h>
int main() {
int subject1, subject2, subject3, subject4, subject5;
float totalMarks, percentage;
// Input marks for each subject
printf("Enter marks for Subject 1: ");
scanf("%d", &subject1);
printf("Enter marks for Subject 2: ");
scanf("%d", &subject2);
printf("Enter marks for Subject 3: ");
scanf("%d", &subject3);
printf("Enter marks for Subject 4: ");
scanf("%d", &subject4);
printf("Enter marks for Subject 5: ");
scanf("%d", &subject5);
// Calculate total marks
totalMarks = subject1 + subject2 + subject3 + subject4 + subject5;
// Calculate percentage
percentage = (totalMarks / (5 * 100)) * 100;
// Display the result
printf("Total Marks: %.2f\n", totalMarks);
printf("Percentage: %.2f%%\n", percentage);
return 0;
}
2. Convert
infix to postfix
Any operation may be written as an infix, prefix, or postfix,
in this C language tutorial, we’ll see how to do this. Two approaches have been
covered: the array-based stack approach and the struct-based stack approach.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_EXPRESSION_SIZE 100
// Define a stack structure
struct Stack {
int top;
char items[MAX_EXPRESSION_SIZE];
};
// Function to initialize the
stack
void initialize(struct Stack
*stack) {
stack->top = -1;
}
// Function to check if the stack
is empty
bool isEmpty(struct Stack *stack)
{
return stack->top == -1;
}
// Function to push an element
onto the stack
void push(struct Stack *stack,
char item) {
if (stack->top == MAX_EXPRESSION_SIZE - 1) {
fprintf(stderr, "Stack overflow\n");
exit(EXIT_FAILURE);
}
stack->items[++stack->top] = item;
}
// Function to pop an element from
the stack
char pop(struct Stack *stack) {
if (isEmpty(stack)) {
fprintf(stderr, "Stack underflow\n");
exit(EXIT_FAILURE);
}
return stack->items[stack->top--];
}
// Function to get the precedence
of an operator
int getPrecedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
}
return 0; // Lower precedence for non-operators
}
// Function to convert infix to
postfix
void infixToPostfix(const char
*infix, char *postfix) {
struct Stack stack;
initialize(&stack);
int i, j;
j = 0;
for (i = 0; infix[i]; i++) {
char token = infix[i];
if (token >= 'a' && token
<= 'z') {
postfix[j++] = token;
} else if (token == '(') {
push(&stack, token);
} else if (token == ')') {
while (!isEmpty(&stack)
&& stack.items[stack.top] != '(') {
postfix[j++] = pop(&stack);
}
if (!isEmpty(&stack) &&
stack.items[stack.top] != '(') {
fprintf(stderr, "Invalid
expression\n");
exit(EXIT_FAILURE);
} else {
pop(&stack); // Pop the '('
from the stack
}
} else {
while (!isEmpty(&stack)
&& getPrecedence(token) <= getPrecedence(stack.items[stack.top])) {
postfix[j++] = pop(&stack);
}
push(&stack, token);
}
}
while (!isEmpty(&stack)) {
char topOperator = pop(&stack);
if (topOperator != '(') {
postfix[j++] = topOperator;
} else {
fprintf(stderr, "Invalid
expression\n");
exit(EXIT_FAILURE);
}
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}
int main() {
char infixExpression[MAX_EXPRESSION_SIZE];
char postfixExpression[MAX_EXPRESSION_SIZE];
printf("Enter an infix expression: ");
fgets(infixExpression, sizeof(infixExpression), stdin);
infixToPostfix(infixExpression, postfixExpression);
printf("Postfix expression: %s\n", postfixExpression);
return 0;
}
3. Odd Even Program
A number is taken into consideration even
though it may be split by two equally. The remainder that is not precisely
divisible by 2 is known as an odd number. Simply expressed, odd numbers adopt
the form n = 2k+1, whereas even numbers take the form n = 2k. Each integer will
be made up of either even or odd integers.
#include <stdio.h>
int main() {
int num;
// Prompt the user for input
printf("Enter an integer: ");
scanf("%d", &num);
// Check if the number is even or odd
if (num % 2 == 0) {
printf("%d is an even
number.\n", num);
} else {
printf("%d is an odd
number.\n", num);
}
return 0;
}
4. Find
area of a circle
Everyone knows the basics
of mathematics,
For finding the area of a
circle, we can get this by performing some
#include <stdio.h>
#include <math.h> // For
using the M_PI constant
int main() {
double radius, area;
// Prompt the user for the radius of the circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
// Calculate the area of the circle
area = M_PI * radius * radius;
// Display the result
printf("The area of the circle with radius %.2lf is %.2lf\n",
radius, area);
return 0;
}
5. Convert Celsius to
Fahrenheit
In the realm of programming, we may easily convert between Celsius
and Fahrenheit by carrying out a few simple mathematical operations.
The formula to change from Celsius
to Fahrenheit is shown below.
#include <stdio.h>
int main() {
double celsius, fahrenheit;
// Prompt the user for the temperature in Celsius
printf("Enter the temperature in Celsius: ");
scanf("%lf", &celsius);
// Convert Celsius to Fahrenheit
fahrenheit = (celsius * 9.0/5.0) + 32;
// Display the result
printf("%.2lf Celsius is equal to %.2lf Fahrenheit\n",
celsius, fahrenheit);
return 0;
}
6. Add
two numbers
In the C programming language, the phrase "sum of two
integers" refers to adding two integer values and printing the addition of
two integer values and the printing of the result. To combine two numbers, all
we need to do is utilize the "+" operator. In the link above, we have
also explained several techniques.
#include <stdio.h>
int main() {
int num1, num2, sum;
// Input the first number
printf("Enter the first
number: ");
scanf("%d", &num1);
// Input the second number
printf("Enter the second number: ");
scanf("%d", &num2);
// Add the two numbers
sum = num1 + num2;
// Display the result
printf("Sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
7. Binary
Search program in C
In the C programming language, a sorted array may be searched
using a technique called binary search by continually halving the search
interval. In order to reduce the time complexity to O, binary search makes use
of the fact that the array is sorted (LogN).
#include <stdio.h>
int binarySearch(int arr[], int
size, int target) {
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Element found,
return its index
} else if (arr[mid] < target) {
left = mid + 1; // Search the right
half
} else {
right = mid - 1; // Search the left
half
}
}
return -1; // Element not found
}
int main() {
int arr[] = {2, 4, 6, 8, 10, 12, 14, 16};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearch(arr, size, target);
if (result != -1) {
printf("Element %d found at index
%d\n", target, result);
} else {
printf("Element %d not found in
the array\n", target);
}
return 0;
}
8. Priority
Scheduling program in C
The algorithms prioritize the processes that must be carried
out and schedule them accordingly. A higher-priority process will receive CPU
priority first, and this will continue until all of the processes are finished.
Due to the process’ greater priority, the Priority Scheduling Algorithm is in
charge of transferring it from the ready queue to the work queue.
#include <stdio.h>
// Structure to represent a
process
struct Process {
int id; // Process ID
int priority; // Priority (lower
value = higher priority)
int burstTime; // Burst time
};
// Function to swap two processes
void swap(struct Process *a,
struct Process *b) {
struct Process temp = *a;
*a = *b;
*b = temp;
}
// Function to perform Priority
Scheduling
void priorityScheduling(struct
Process processes[], int n) {
// Sort processes based on priority (in ascending order)
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++)
{
if (processes[j].priority >
processes[j + 1].priority) {
swap(&processes[j],
&processes[j + 1]);
}
}
}
// Display the order of execution
printf("Process Execution Order:\n");
for (int i = 0; i < n; i++) {
printf("Process %d (Priority
%d)\n", processes[i].id, processes[i].priority);
}
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
struct Process processes[n];
// Input process details
for (int i = 0; i < n; i++) {
printf("Enter details for Process
%d:\n", i + 1);
processes[i].id = i + 1;
printf("Priority: ");
scanf("%d",
&processes[i].priority);
printf("Burst Time: ");
scanf("%d",
&processes[i].burstTime);
}
// Perform Priority Scheduling
priorityScheduling(processes, n);
return 0;
}
9. Find
roots of quadratic equation
A quadratic has the formula y = ax^2 + bx + c, where a, b, and
c are all integers and a must be 0. An illustration of a quadratic equation is
3×2 + 3x + 1.
Let’s talk about what a quadratic equation’s roots are and how
to get them from the equation.
The discriminant of a quadratic equation is the expression b2 –
4ac. It describes the roots’ character.
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double discriminant, root1, root2;
// Input coefficients a, b, and c
printf("Enter coefficients a, b, and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Check the nature of the roots
if (discriminant > 0) {
// Two distinct real roots
root1 = (-b + sqrt(discriminant)) / (2
* a);
root2 = (-b - sqrt(discriminant)) / (2
* a);
printf("Roots are real and
distinct:\n");
printf("Root 1 = %.2lf\n",
root1);
printf("Root 2 = %.2lf\n",
root2);
} else if (discriminant == 0) {
// One real root (repeated)
root1 = -b / (2 * a);
printf("Roots are real and
repeated:\n");
printf("Root 1 = Root 2 =
%.2lf\n", root1);
} else {
// Complex roots
double realPart = -b / (2 * a);
double imaginaryPart =
sqrt(-discriminant) / (2 * a);
printf("Roots are
complex:\n");
printf("Root 1 = %.2lf +
%.2lfi\n", realPart, imaginaryPart);
printf("Root 2 = %.2lf -
%.2lfi\n", realPart, imaginaryPart);
}
return 0;
}
10. Convert
binary numbers to decimal number
In order to convert a binary number to a decimal number, we
must multiply each digit of the binary number starting at 0 by powers of 2 and
then sum the results to obtain the decimal number.
#include <stdio.h>
#include <math.h>
int main() {
long long binaryNumber;
int decimalNumber = 0, i = 0, remainder;
// Input binary number from the user
printf("Enter a binary number: ");
scanf("%lld", &binaryNumber);
// Convert binary to decimal
while (binaryNumber != 0) {
remainder = binaryNumber % 10;
decimalNumber += remainder * pow(2, i);
++i;
binaryNumber /= 10;
}
printf("Decimal equivalent: %d\n", decimalNumber);
return 0;
}
11. Ascending
order program in C language
Different kinds of reasoning can be used to sort things. For
the sake of simplicity, we shall employ a tried-and-true technique. We choose a
certain element from an array, compare it to other elements, and then place it
appropriately to sort the array.
#include <stdio.h>
void bubbleSort(int arr[], int n)
{
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap them if they are in the
wrong order
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sort the array in ascending order
bubbleSort(arr, n);
printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
12. SJF
Scheduling program in C
One of the CPU scheduling strategies is to select the shortest
jobs first. It is an algorithm whose burst time-dependent procedure. In other
words, a process with a lower burst time executes first. The shortest job next
(SJN) is another name for the shortest job first (SJF). For instance, we have
four processes, P1, P2, P3, and P4, with burst times of 5, 7, 6, and 2. Process
P4 will now be run first since it has a shorter burst period. Processes P1, P3,
and P2 will then be carried out in that order.
#include <stdio.h>
void findWaitingTime(int
processes[], int n, int bt[], int wt[]) {
wt[0] = 0;
for (int i = 1; i < n; i++) {
wt[i] = 0;
for (int j = 0; j < i; j++) {
wt[i] += bt[j];
}
}
}
void findTurnaroundTime(int
processes[], int n, int bt[], int wt[], int tat[]) {
for (int i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
}
}
void findAverageTime(int
processes[], int n, int bt[]) {
int wt[n], tat[n];
findWaitingTime(processes, n, bt, wt);
findTurnaroundTime(processes, n, bt, wt, tat);
float total_wt = 0, total_tat = 0;
for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}
float avg_wt = total_wt / n;
float avg_tat = total_tat / n;
printf("Process\tBurst Time\tWaiting Time\tTurnaround
Time\n");
for (int i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", processes[i], bt[i], wt[i],
tat[i]);
}
printf("Average Waiting Time: %.2f\n", avg_wt);
printf("Average Turnaround Time: %.2f\n", avg_tat);
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
int processes[n];
int burst_time[n];
printf("Enter the burst times for each process:\n");
for (int i = 0; i < n; i++) {
printf("Burst Time for P%d:
", i + 1);
scanf("%d",
&burst_time[i]);
processes[i] = i + 1;
}
findAverageTime(processes, n, burst_time);
return 0;
}
13. Menu
Driven program for all operations on the doubly linked list in C.
In the menu-driven program in C, the user is given a variety of
options, and some functionality is available based on these choices. These
programs are used to give users the desired functions and a straightforward yet
effective user interface.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
typedef struct Node Node;
Node* createNode(int data) {
Node*
newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation
failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
Node* insertFront(Node* head, int
data) {
Node* newNode = createNode(data);
if (head == NULL) {
return newNode;
}
newNode->next = head;
head->prev = newNode;
return newNode;
}
Node* insertEnd(Node* head, int
data) {
Node* newNode = createNode(data);
if (head == NULL) {
return newNode;
}
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
return head;
}
Node* deleteFront(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return NULL;
}
Node* temp = head;
head = head->next;
if (head != NULL) {
head->prev = NULL;
}
free(temp);
return head;
}
Node* deleteEnd(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return NULL;
}
if (head->next == NULL) {
free(head);
return NULL;
}
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->prev->next = NULL;
free(current);
return head;
}
void displayList(Node* head) {
printf("Doubly Linked List: ");
while (head != NULL) {
printf("%d <-> ",
head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL;
int choice, data;
do {
printf("\nMenu:\n");
printf("1. Insert at the front\n");
printf("2. Insert at the
end\n");
printf("3. Delete from the
front\n");
printf("4. Delete from the
end\n");
printf("5. Display the
list\n");
printf("6. Exit\n");
printf("Enter your choice:
");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to
insert: ");
scanf("%d",
&data);
head = insertFront(head, data);
break;
case 2:
printf("Enter data to
insert: ");
scanf("%d",
&data);
head = insertEnd(head, data);
break;
case 3:
head = deleteFront(head);
break;
case 4:
head = deleteEnd(head);
break;
case 5:
displayList(head);
break;
case 6:
printf("Exiting the
program.\n");
break;
default:
printf("Invalid choice.
Please try again.\n");
}
} while (choice != 6);
return 0;
}
14. FCFS
Scheduling program in C
The CPU assigns work using a non-preemptive scheduling
mechanism called First Come First Serve. According to the request that was made
initially, as the name implies, the tasks are given the highest priority.
#include <stdio.h>
// Function to calculate waiting
time and turnaround time
void findWaitingTime(int
processes[], int n, int bt[], int wt[]) {
// Waiting time for the first process is always 0
wt[0] = 0;
// Calculate waiting time for each process
for (int i = 1; i < n; i++) {
wt[i] = bt[i - 1] + wt[i - 1];
}
}
// Function to calculate
turnaround time
void findTurnaroundTime(int
processes[], int n, int bt[], int wt[], int tat[]) {
// Calculate turnaround time for each process
for (int i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
}
}
// Function to calculate average
time
void findAverageTime(int
processes[], int n, int bt[]) {
int wt[n], tat[n];
double total_wt = 0, total_tat = 0;
// Find waiting time of all processes
findWaitingTime(processes, n, bt, wt);
// Find turnaround time of all processes
findTurnaroundTime(processes, n, bt, wt, tat);
// Calculate total waiting time and total turnaround time
for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}
// Calculate and print average waiting time and average turnaround time
double avg_wt = total_wt / n;
double avg_tat = total_tat / n;
printf("Average Waiting Time: %.2lf\n", avg_wt);
printf("Average Turnaround Time: %.2lf\n", avg_tat);
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
int processes[n];
int burst_time[n];
// Input burst times for each process
printf("Enter burst times for each process:\n");
for (int i = 0; i < n; i++) {
printf("Burst time for Process %d:
", i + 1);
scanf("%d",
&burst_time[i]);
processes[i] = i + 1; // Assign process
numbers
}
// Calculate and display average waiting time and turnaround time
findAverageTime(processes, n, burst_time);
return 0;
}
15. Swap
two Numbers
When two numbers are changed, two variables’ values are also
changed. Think about the variables var1 and var2 you have. Var1 is valued at
20, whereas Var2 is valued at 40. As a result, after swapping, var1 and var2
will have values of 40 and 20, respectively.
We have discussed different
methods such as:
1. Swapping Two Numbers Using a Third Variable
#include <stdio.h>
int main() {
int var1 = 20;
int var2 = 40;
int temp;
printf("Before swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
// Swap the values using a temporary variable
temp = var1;
var1 = var2;
var2 = temp;
printf("After swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
return 0;
}
2. Swapping Two Numbers Using Without Using Third Variable
#include <stdio.h>
int main() {
int var1 = 20;
int var2 = 40;
printf("Before swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
// Swap the values without using a temporary variable
var1 = var1 + var2;
var2 = var1 - var2;
var1 = var1 - var2;
printf("After swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
return 0;
}
3. Swapping Function in C
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int var1 = 20;
int var2 = 40;
printf("Before swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
swap(&var1, &var2);
printf("After swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
return 0;
}
4. Swap two numbers using pointers in C
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int var1 = 20;
int var2 = 40;
printf("Before swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
swap(&var1, &var2);
printf("After swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
return 0;
}
5. Swap Two Numbers Using Bitwise XOR
#include <stdio.h>
int main() {
int var1 = 20;
int var2 = 40;
printf("Before swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
// Swap the values using bitwise XOR
var1 = var1 ^ var2;
var2 = var1 ^ var2;
var1 = var1 ^ var2;
printf("After swapping:\n");
printf("var1 = %d\n", var1);
printf("var2 = %d\n", var2);
return 0;
}
16. Compound
Interest Program
To calculate the amount of
interest given by:
Amount of interest =
P(1+R/100)t
P = Principal amount
R = Rate of interest
T = The Time span
Compound Interest = Amount – P
#include <stdio.h>
#include <math.h>
int main() {
double principal, rate, time, amount, compoundInterest;
// Input principal amount
printf("Enter the principal amount: ");
scanf("%lf", &principal);
// Input rate of interest
printf("Enter the rate of interest (in percentage): ");
scanf("%lf", &rate);
// Input time span
printf("Enter the time span (in years): ");
scanf("%lf", &time);
// Calculate amount
amount = principal * pow((1 + rate / 100), time);
// Calculate compound interest
compoundInterest = amount - principal;
// Display the results
printf("Amount after %.2lf years: %.2lf\n", time, amount);
printf("Compound Interest after %.2lf years: %.2lf\n", time,
compoundInterest);
return 0;
}
17. Radix
Sort Program
Each digit is sorted in the Radix sort algorithm from least to
greatest significance. In base 10, radix sort would first sort by the digits in
the place of one, then by the digits in the place of ten, and so on. Radix sort
uses counting sort as a subroutine to order the data in each digit position.
#include <stdio.h>
// Function to find the maximum
element in the array
int findMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// A function to do counting sort
based on the digit represented by exp.
void countSort(int arr[], int n,
int exp) {
int output[n]; // Output array
int count[10] = {0};
// Count occurrences of digits at the current digit place
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
// Modify count[i] to store the position of the digit in output
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1]
= arr[i];
count[(arr[i] / exp) % 10]--;
}
// Copy the output array to arr[], so that arr[] contains the sorted
numbers
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
// Radix Sort function
void radixSort(int arr[], int n) {
// Find the maximum number to know the number of digits
int max = findMax(arr, n);
// Do counting sort for every digit, starting from the least significant
digit
for (int exp = 1; max / exp > 0; exp *= 10) {
countSort(arr, n, exp);
}
}
// Function to print an array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
radixSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
18. Bubble
sort on Linked List
The bubble sort’s fundamental principle is to
compare each member of an array individually until they are sorted in ascending
order, a process known as bubble busting. Instead of shifting the entire array
when an element has to be moved, the impacted element is just moved.
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the
linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation
failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to append a node to
the end of the linked list
void appendNode(struct Node**
head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// Function to perform Bubble Sort
on a linked list
void bubbleSort(struct Node* head)
{
int swapped;
struct Node* ptr1;
struct Node* lptr = NULL;
// Checking for empty list
if (head == NULL) {
return;
}
do {
swapped = 0;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data >
ptr1->next->data) {
// Swap data of the two nodes
int temp = ptr1->data;
ptr1->data =
ptr1->next->data;
ptr1->next->data = temp;
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
// Function to print the linked
list
void printList(struct Node* head)
{
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// Appending elements to the linked list
appendNode(&head, 64);
appendNode(&head, 34);
appendNode(&head, 25);
appendNode(&head, 12);
appendNode(&head, 22);
printf("Original Linked List: ");
printList(head);
bubbleSort(head);
printf("Linked List after Bubble Sort: ");
printList(head);
return 0;
}
19. Round-Robin
Scheduling
With round-robin scheduling, each job receives an equal amount
of CPU time. In its most basic form, jobs are placed in a circular queue, where
they are moved to the back of the queue when their allotted CPU time runs out
and to the front when a new task is added.
#include <stdio.h>
#include <stdlib.h>
#define MAX_JOBS 100
struct Job {
int id;
int burst_time;
int remaining_time;
};
struct Queue {
struct Job* jobs[MAX_JOBS];
int front, rear, size;
};
struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->size = 0;
queue->rear = MAX_JOBS - 1;
return queue;
}
int isQueueFull(struct Queue*
queue) {
return (queue->size == MAX_JOBS);
}
int isQueueEmpty(struct Queue*
queue) {
return (queue->size == 0);
}
void enqueue(struct Queue* queue,
struct Job* job) {
if (isQueueFull(queue)) {
printf("Queue is full. Cannot
enqueue more jobs.\n");
return;
}
queue->rear = (queue->rear + 1) % MAX_JOBS;
queue->jobs[queue->rear] = job;
queue->size++;
}
struct Job* dequeue(struct Queue*
queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty. Cannot
dequeue.\n");
return NULL;
}
struct Job* job = queue->jobs[queue->front];
queue->front = (queue->front + 1) % MAX_JOBS;
queue->size--;
return job;
}
int main() {
int num_jobs, time_quantum;
printf("Enter the number of jobs: ");
scanf("%d", &num_jobs);
printf("Enter the time
quantum: ");
scanf("%d", &time_quantum);
struct Queue* job_queue = createQueue();
for (int i = 0; i < num_jobs; i++) {
struct Job* job = (struct
Job*)malloc(sizeof(struct Job));
job->id = i + 1;
printf("Enter burst time for Job
%d: ", job->id);
scanf("%d",
&job->burst_time);
job->remaining_time =
job->burst_time;
enqueue(job_queue, job);
}
printf("\nRound-Robin Scheduling:\n");
int total_time = 0;
while (!isQueueEmpty(job_queue)) {
struct Job* current_job =
dequeue(job_queue);
int execution_time =
(current_job->remaining_time < time_quantum) ?
current_job->remaining_time : time_quantum;
current_job->remaining_time -=
execution_time;
total_time += execution_time;
printf("Job %d executed for %d
units of time. Remaining time: %d\n", current_job->id, execution_time,
current_job->remaining_time);
if (current_job->remaining_time >
0) {
enqueue(job_queue, current_job);
} else {
free(current_job);
}
}
printf("\nTotal execution time: %d\n", total_time);
return 0;
}
20. Reverse
a Number
Using the modulo division (%) function, find the final digit of
the provided integer, and then save the result in the last digit variable, for
example, last digit=number%10. Reversed is equal to reversed times 10 plus the
final digit, therefore reversed is reversed times 10 plus the last digit. Like
numbered/10, multiply the number by 10.
#include <stdio.h>
int main() {
int number, reversed = 0;
// Input the number from the user
printf("Enter an integer: ");
scanf("%d", &number);
// Reverse the number using modulo division
while (number != 0) {
int lastDigit = number % 10; // Get the last digit
reversed = reversed * 10 + lastDigit;
// Reverse the number
number = number / 10; // Remove the
last digit
}
// Display the reversed number
printf("Reversed number: %d\n", reversed);
return 0;
}
- Get link
- X
- Other Apps
Popular Posts
Artificial intelligence
- Get link
- X
- Other Apps
Datatype Programming in C, Data Type
- Get link
- X
- Other Apps
Computer Virus Describe in Hindi
- Get link
- X
- Other Apps
Getting Started C Programming
- Get link
- X
- Other Apps
In C, variable names must adhere to certain rules and conventions. Here are some examples of valid and invalid variable names and the reasons why:
- Get link
- X
- Other Apps
Decision Control Structure in C, Boolean Operator and Expression
- Get link
- X
- Other Apps
Operators and Expressions in C Programming
- Get link
- X
- Other Apps
Operators in Java
- Get link
- X
- Other Apps
Comments
Post a Comment