0% found this document useful (0 votes)
4 views38 pages

C Programming Basics: 16 Examples

The document contains a series of C programming code snippets, each demonstrating different programming concepts such as calculating the area and circumference of a circle, swapping numbers, summing natural numbers, checking for vowels, finding the largest number, calculating sums of even numbers, and more. Each code snippet includes user input, processing logic, and output display. The examples cover a range of topics including loops, functions, recursion, arrays, strings, and matrix operations.

Uploaded by

rkpandey12346789
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)
4 views38 pages

C Programming Basics: 16 Examples

The document contains a series of C programming code snippets, each demonstrating different programming concepts such as calculating the area and circumference of a circle, swapping numbers, summing natural numbers, checking for vowels, finding the largest number, calculating sums of even numbers, and more. Each code snippet includes user input, processing logic, and output display. The examples cover a range of topics including loops, functions, recursion, arrays, strings, and matrix operations.

Uploaded by

rkpandey12346789
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

Q1

#include <stdio.h>

#define PI 3.14159

int main() {

float radius, area, circumference;

// Input radius from user

printf("Enter the radius of the circle: ");

scanf("%f", &radius);

// Calculate area

area = PI * radius * radius;

// Calculate circumference

circumference = 2 * PI * radius;

// Display results

printf("Area of the circle: %.2f\n", area);

printf("Circumference of the circle: %.2f\n", circumference);

return 0;

}
Q2
#include <stdio.h>

int main() {

int a, b, temp;

// Input values of a and b from user

printf("Enter the value of a: ");

scanf("%d", &a);

printf("Enter the value of b: ");

scanf("%d", &b);

// Swapping logic

temp = a;

a = b;

b = temp;

// Displaying swapped values

printf("After swapping:\n");

printf("a = %d\n", a);

printf("b = %d\n", b);

return 0;

}
Q3
#include <stdio.h>

int main() {

int n, sum = 0;

// Input a positive integer from user

printf("Enter a positive integer: ");

scanf("%d", &n);

// Calculate sum of natural numbers up to n

for (int i = 1; i <= n; i++) {

sum += i;

// Display the sum

printf("Sum of natural numbers from 1 to %d is %d\n", n, sum);

return 0;

}
Q4

#include <stdio.h>

int main() {

char alphabet;

// Input alphabet from user

printf("Enter an alphabet: ");

scanf(" %c", &alphabet); // Note the space before %c to consume any leading whitespace

// Check if the input is a lowercase vowel

if (alphabet == 'a' || alphabet == 'e' || alphabet == 'i' || alphabet == 'o' || alphabet == 'u')

printf("%c is a vowel.\n", alphabet);

// Check if the input is an uppercase vowel

else if (alphabet == 'A' || alphabet == 'E' || alphabet == 'I' || alphabet == 'O' || alphabet == 'U')

printf("%c is a vowel.\n", alphabet);

// Check if the input is a consonant

else if ((alphabet >= 'a' && alphabet <= 'z') || (alphabet >= 'A' && alphabet <= 'Z'))

printf("%c is a consonant.\n", alphabet);

// If input is not an alphabet

else

printf("Invalid input. Please enter an alphabet.\n");

return 0;

}
Q5

#include <stdio.h>

int main() {

int num1, num2, num3;

// Input three numbers from user

printf("Enter three numbers: ");

scanf("%d %d %d", &num1, &num2, &num3);

// Check which number is the largest

if (num1 >= num2 && num1 >= num3)

printf("%d is the largest number.\n", num1);

else if (num2 >= num1 && num2 >= num3)

printf("%d is the largest number.\n", num2);

else

printf("%d is the largest number.\n", num3);

return 0;

}
Q6

#include <stdio.h>

int main() {

int sum = 0;

// Calculate sum of even numbers up to 100

for (int i = 2; i <= 100; i += 2) {

sum += i;

// Display the sum

printf("Sum of even numbers from 1 to 100 is %d\n", sum);

return 0;

}
Q7

#include <stdio.h>

// Function to calculate the factorial of a number

int factorial(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * factorial(n - 1);

int main() {

int num, sum = 0;

// Input a number from user

printf("Enter a number: ");

scanf("%d", &num);

// Calculate sum of factorial values up to the given number

for (int i = 1; i <= num; i++) {

sum += factorial(i);

// Display the sum of factorial values

printf("Sum of factorial values up to %d is %d\n", num, sum);

return 0;

}
Q8

#include <stdio.h>

// Function to reverse a number

int reverseNumber(int num) {

int reversed = 0;

while (num != 0) {

int remainder = num % 10;

reversed = reversed * 10 + remainder;

num /= 10;

return reversed;

// Function to check if a number is palindrome

int isPalindrome(int num) {

int reversed = reverseNumber(num);

return num == reversed;

int main() {

int number;

// Input a number from user

printf("Enter a number: ");

scanf("%d", &number);

// Display the number in reverse order

printf("Number in reverse order: %d\n", reverseNumber(number));

// Check if the number is palindrome


if (isPalindrome(number))

printf("The number is a palindrome.\n");

else

printf("The number is not a palindrome.\n");

return 0;

}
Q9 #include <stdio.h>

#include <stdbool.h>

// Function to check if a number is prime

bool isPrime(int num) {

if (num <= 1)

return false; // Numbers less than or equal to 1 are not prime

// Check for factors from 2 to sqrt(num)

for (int i = 2; i * i <= num; i++) {

if (num % i == 0)

return false; // If a factor is found, the number is not prime

return true; // If no factors found, the number is prime

int main() {

int number;

// Input a number from user

printf("Enter a number: ");

scanf("%d", &number);

// Check if the number is prime

if (isPrime(number))

printf("%d is a prime number.\n", number);

else

printf("%d is not a prime number.\n", number);

return 0;

}
Q10

#include <stdio.h>

#include <stdbool.h>

// Function to check if a number is prime

bool isPrime(int num) {

if (num <= 1)

return false; // Numbers less than or equal to 1 are not prime

// Check for factors from 2 to sqrt(num)

for (int i = 2; i * i <= num; i++) {

if (num % i == 0)

return false; // If a factor is found, the number is not prime

return true; // If no factors found, the number is prime

int main() {

printf("Prime numbers up to 100 are:\n");

// Check and print prime numbers from 2 to 100

for (int i = 2; i <= 100; i++) {

if (isPrime(i))

printf("%d ", i);

printf("\n");

return 0;

}
Q11

#include <stdio.h>

int main() {

int number, sum = 0, digit;

// Input a number from user

printf("Enter a number: ");

scanf("%d", &number);

// Calculate the sum of digits

while (number != 0) {

digit = number % 10; // Extract the last digit

sum += digit; // Add the digit to the sum

number /= 10; // Remove the last digit

// Display the sum of digits

printf("Sum of digits: %d\n", sum);

return 0;

}
Q12

#include <stdio.h>

// Function to calculate the Greatest Common Divisor (GCD)

int gcd(int a, int b) {

if (b == 0)

return a;

return gcd(b, a % b);

// Function to calculate the Least Common Multiple (LCM)

int lcm(int a, int b) {

return (a * b) / gcd(a, b);

int main() {

int num1, num2;

// Input two numbers from user

printf("Enter two numbers: ");

scanf("%d %d", &num1, &num2);

// Calculate and display the LCM

printf("LCM of %d and %d is %d\n", num1, num2, lcm(num1, num2));

return 0;

}
Q13

#include <stdio.h>

// Function to calculate the Greatest Common Divisor (GCD) using Euclidean algorithm

int gcd(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

int main() {

int num1, num2;

// Input two numbers from user

printf("Enter two numbers: ");

scanf("%d %d", &num1, &num2);

// Calculate and display the GCD

printf("GCD of %d and %d is %d\n", num1, num2, gcd(num1, num2));

return 0;

}
Q14

#include <stdio.h>

// Recursive function to calculate factorial

int factorial(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * factorial(n - 1);

int main() {

int num;

// Input a number from user

printf("Enter a non-negative integer: ");

scanf("%d", &num);

// Calculate factorial using recursive function

printf("Factorial of %d is %d\n", num, factorial(num));

return 0;

}
Q15

#include <stdio.h>

// Function to calculate the sum of two numbers

int sum(int num1, int num2) {

return num1 + num2;

int main() {

int number1, number2;

// Input two numbers from user

printf("Enter first number: ");

scanf("%d", &number1);

printf("Enter second number: ");

scanf("%d", &number2);

// Calculate the sum using the sum function and display the result

printf("Sum of %d and %d is %d\n", number1, number2, sum(number1, number2));

return 0;

}
Q16

#include <stdio.h>

#include <math.h>

int main() {

double x = 4.0;

double y = 2.0;

// Demonstrate some math functions

printf("Square root of %.2f = %.2f\n", x, sqrt(x));

printf("Power of %.2f raised to %.2f = %.2f\n", x, y, pow(x, y));

printf("Absolute value of %.2f = %.2f\n", -x, fabs(-x));

printf("Natural logarithm of %.2f = %.2f\n", x, log(x));

printf("Logarithm base 10 of %.2f = %.2f\n", x, log10(x));

printf("Ceiling of %.2f = %.2f\n", x, ceil(x));

printf("Floor of %.2f = %.2f\n", x, floor(x));

printf("Rounded value of %.2f = %.2f\n", 4.5, round(4.5));

return 0;

}
Q17

#include <stdio.h>

// Function to find the maximum value in an 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;

// Function to find the minimum value in an array

int findMin(int arr[], int n) {

int min = arr[0];

for (int i = 1; i < n; i++) {

if (arr[i] < min) {

min = arr[i];

return min;

int main() {

int arr[] = {5, 7, 3, 9, 2, 6};

int size = sizeof(arr) / sizeof(arr[0]);

// Find maximum and minimum values in the array

int maximum = findMax(arr, size);


int minimum = findMin(arr, size);

// Display the maximum and minimum values

printf("Maximum value in the array: %d\n", maximum);

printf("Minimum value in the array: %d\n", minimum);

return 0;

}
Q18

#include <stdio.h>

#define ROWS 3

#define COLS 3

// Function to add two matrices

void addMatrices(int mat1[][COLS], int mat2[][COLS], int result[][COLS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

result[i][j] = mat1[i][j] + mat2[i][j];

// Function to display a matrix

void displayMatrix(int mat[][COLS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

printf("%d ", mat[i][j]);

printf("\n");

int main() {

int matrix1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int matrix2[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

int result[ROWS][COLS];

// Add two matrices


addMatrices(matrix1, matrix2, result);

// Display the matrices and the result

printf("Matrix 1:\n");

displayMatrix(matrix1);

printf("\nMatrix 2:\n");

displayMatrix(matrix2);

printf("\nResult of addition:\n");

displayMatrix(result);

return 0;

}
Q19

#include <stdio.h>

#include <string.h>

int main() {

char str1[50] = "Hello";

char str2[50] = "World";

// strlen(): Get length of a string

printf("Length of str1: %lu\n", strlen(str1));

// strcat(): Concatenate two strings

strcat(str1, " ");

strcat(str1, str2);

printf("Concatenated string: %s\n", str1);

// strcpy(): Copy a string

char str3[50];

strcpy(str3, str1);

printf("Copied string: %s\n", str3);

// strcmp(): Compare two strings

char str4[] = "Apple";

char str5[] = "Banana";

int result = strcmp(str4, str5);

if (result == 0)

printf("%s is equal to %s\n", str4, str5);

else if (result < 0)

printf("%s comes before %s\n", str4, str5);

else

printf("%s comes after %s\n", str4, str5);


// strchr(): Find first occurrence of a character in a string

char *ptr = strchr(str1, 'W');

if (ptr != NULL)

printf("Character 'W' found at index: %ld\n", ptr - str1);

else

printf("Character 'W' not found in the string.\n");

// strstr(): Find first occurrence of a substring in a string

ptr = strstr(str1, "World");

if (ptr != NULL)

printf("Substring 'World' found at index: %ld\n", ptr - str1);

else

printf("Substring 'World' not found in the string.\n");

return 0;

}
Q20

#include <stdio.h>

int main() {

// Array of pointers to integers

int *ptrArray[3];

// Array of integers

int arr1[] = {10, 20, 30};

int arr2[] = {40, 50, 60};

int arr3[] = {70, 80, 90};

// Assigning addresses of arrays to pointers in the array of pointers

ptrArray[0] = arr1;

ptrArray[1] = arr2;

ptrArray[2] = arr3;

// Accessing elements using array of pointers

printf("Values using array of pointers:\n");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", *(ptrArray[i] + j));

printf("\n");

return 0;

}
Q21
#include <stdio.h>

// Function to swap two integers using call by value

void swapByValue(int a, int b) {

int temp = a;

a = b;

b = temp;

// Function to swap two integers using call by reference

void swapByReference(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

int main() {

int x = 5, y = 10;

printf("Before swapping:\n");

printf("x = %d, y = %d\n", x, y);

// Call by value

swapByValue(x, y);

printf("After swapping by value:\n");

printf("x = %d, y = %d\n", x, y);

// Call by reference

swapByReference(&x, &y);

printf("After swapping by reference:\n");

printf("x = %d, y = %d\n", x, y);

return 0;

}
Q22

#include <stdio.h>

// Global variable with external linkage

int global_var = 10;

// Function with internal linkage (static function)

static void staticFunction() {

printf("Inside static function\n");

int main() {

// Automatic variable with block scope

int auto_var = 20;

// Register variable

register int reg_var = 30;

// Static variable with block scope

static int static_var = 40;

// Output values

printf("Global variable: %d\n", global_var);

printf("Automatic variable: %d\n", auto_var);

printf("Register variable: %d\n", reg_var);

printf("Static variable: %d\n", static_var);

// Call static function

staticFunction();

return 0;

}
Q23

#include <stdio.h>

// Define a structure to represent student

struct Student {

char name[50];

int marks[5];

float total;

float average;

char result[10];

};

// Function to calculate total marks of a student

float calculateTotal(struct Student s) {

float total = 0;

for (int i = 0; i < 5; i++) {

total += [Link][i];

return total;

// Function to calculate average marks of a student

float calculateAverage(struct Student s) {

return [Link] / 5;

// Function to determine result based on average marks

void determineResult(struct Student *s) {

if (s->average >= 60)

strcpy(s->result, "Pass");

else
strcpy(s->result, "Fail");

int main() {

// Create an instance of Student structure

struct Student student1 = {"John", {85, 90, 75, 80, 95}, 0, 0, ""};

// Calculate total marks

[Link] = calculateTotal(student1);

// Calculate average marks

[Link] = calculateAverage(student1);

// Determine result

determineResult(&student1);

// Display student information

printf("Name: %s\n", [Link]);

printf("Total marks: %.2f\n", [Link]);

printf("Average marks: %.2f\n", [Link]);

printf("Result: %s\n", [Link]);

return 0;

}
Q24

#include <stdio.h>

#include <string.h>

// Define a union to represent various data types

union Data {

int i;

float f;

char str[20];

};

int main() {

union Data data;

// Assign values to different members of the union

data.i = 10;

printf("Integer value: %d\n", data.i);

data.f = 3.14;

printf("Float value: %.2f\n", data.f);

strcpy([Link], "Hello");

printf("String value: %s\n", [Link]);

// Size of the union

printf("Size of union Data: %lu bytes\n", sizeof(union Data));

return 0;

}
Q25

#include <stdio.h>

// Enumeration of days of the week

enum DaysOfWeek {

SUNDAY,

MONDAY,

TUESDAY,

WEDNESDAY,

THURSDAY,

FRIDAY,

SATURDAY

};

int main() {

// Declare variables of enumerated type

enum DaysOfWeek today, tomorrow;

// Assign values to variables

today = MONDAY;

tomorrow = TUESDAY;

// Print values of variables

printf("Today is ");

switch (today) {

case SUNDAY:

printf("Sunday");

break;

case MONDAY:

printf("Monday");

break;
case TUESDAY:

printf("Tuesday");

break;

case WEDNESDAY:

printf("Wednesday");

break;

case THURSDAY:

printf("Thursday");

break;

case FRIDAY:

printf("Friday");

break;

case SATURDAY:

printf("Saturday");

break;

printf("\n");

printf("Tomorrow is ");

switch (tomorrow) {

case SUNDAY:

printf("Sunday");

break;

case MONDAY:

printf("Monday");

break;

case TUESDAY:

printf("Tuesday");

break;

case WEDNESDAY:

printf("Wednesday");
break;

case THURSDAY:

printf("Thursday");

break;

case FRIDAY:

printf("Friday");

break;

case SATURDAY:

printf("Saturday");

break;

printf("\n");

return 0;

}
Q26

#include <stdio.h>

// Define a structure to represent a student

struct Student {

char name[50];

int rollNumber;

float marks;

};

// Function to initialize a student

void initializeStudent(struct Student *student, const char *name, int rollNumber, float marks) {

strcpy(student->name, name);

student->rollNumber = rollNumber;

student->marks = marks;

// Function to display student information

void displayStudent(const struct Student *student) {

printf("Name: %s\n", student->name);

printf("Roll Number: %d\n", student->rollNumber);

printf("Marks: %.2f\n", student->marks);

int main() {

// Declare and initialize a student

struct Student student1;

initializeStudent(&student1, "John Doe", 101, 85.5);

// Display student information

displayStudent(&student1);

return 0;

}
Q27

#include <stdio.h>

#include <stdarg.h>

// Function to calculate sum of integers

int sumIntegers(int count, ...) {

int sum = 0;

va_list args;

va_start(args, count);

for (int i = 0; i < count; i++) {

sum += va_arg(args, int);

va_end(args);

return sum;

// Function to calculate sum of floats

float sumFloats(int count, ...) {

float sum = 0;

va_list args;

va_start(args, count);

for (int i = 0; i < count; i++) {

sum += va_arg(args, double); // Promote to double before summing

va_end(args);

return sum;

int main() {

printf("Sum of 3 integers: %d\n", sumIntegers(3, 10, 20, 30));

printf("Sum of 4 floats: %.2f\n", sumFloats(4, 3.5, 2.5, 4.5, 6.5));

return 0;

}
Q28

#include <stdio.h>

#include <string.h>

// Define a structure to represent a student

struct Student {

char name[50];

int rollNumber;

float marks;

};

// Function to initialize a student

void initializeStudent(struct Student *student, const char *name, int rollNumber, float marks) {

strcpy(student->name, name);

student->rollNumber = rollNumber;

student->marks = marks;

// Function to display student information

void displayStudent(const struct Student *student) {

printf("Name: %s\n", student->name);

printf("Roll Number: %d\n", student->rollNumber);

printf("Marks: %.2f\n", student->marks);

int main() {

// Declare and initialize a student using initialization function

struct Student student1;

initializeStudent(&student1, "John Doe", 101, 85.5);

// Display student information

displayStudent(&student1);

return 0;

}
Q29

COMPOSITION

#include <stdio.h>

// Base class

struct Shape {

int width;

int height;

};

// Derived class

struct Rectangle {

struct Shape shape;

};

// Function to calculate area of rectangle

int calculateArea(struct Rectangle *rect) {

return rect->[Link] * rect->[Link];

int main() {

// Create an instance of Rectangle

struct Rectangle rect;

[Link] = 5;

[Link] = 10;

// Calculate and print area

printf("Area of rectangle: %d\n", calculateArea(&rect));

return 0;

}
Pointer-based Polymorphism:
#include <stdio.h>

// Base class

struct Shape {

int width;

int height;

int (*area)(void *);

};

// Function to calculate area of rectangle

int rectangleArea(void *ptr) {

struct Shape *shape = (struct Shape *)ptr;

return shape->width * shape->height;

int main() {

// Create an instance of Shape (Rectangle)

struct Shape rect;

[Link] = 5;

[Link] = 10;

[Link] = rectangleArea;

// Calculate and print area

printf("Area of rectangle: %d\n", [Link](&rect));

return 0;

}
Q30

#include <stdio.h>

// Function to calculate electricity bill

float calculateBill(int units) {

float bill;

if (units <= 50)

bill = units * 0.50;

else if (units <= 150)

bill = 25 + (units - 50) * 0.75;

else if (units <= 250)

bill = 100 + (units - 150) * 1.20;

else

bill = 220 + (units - 250) * 1.50;

return bill;

int main() {

int units;

float bill;

// Input units consumed from user

printf("Enter units consumed: ");

scanf("%d", &units);

// Calculate electricity bill

bill = calculateBill(units);

// Display the bill amount

printf("Electricity bill: %.2f\n", bill);

return 0;

You might also like