C Operators and Programming Examples
C Operators and Programming Examples
A. Arithme c Operators: Perform basic arithme c opera ons like addi on, subtrac on,
mul plica on, and division.
+ (Addi on)
- (Subtrac on)
* (Mul plica on)
/ (Division)
B. Rela onal Operators: Compare values and determine rela onships between them.
> (Greater than)
< (Less than)
== (Equal to)
!= (Not equal to)
C. Logical Operators: Perform logical opera ons on boolean values.
&& (Logical AND)
|| (Logical OR)
! (Logical NOT)
D. Bitwise Operators: Perform opera ons at the bit level.
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
<< (Le shi )
>> (Right shi )
E. Assignment Operators: Assign values to variables and perform an opera on in the same
step.
= (Assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Mul ply and assign)
/= (Divide and assign)
%= (Modulo and assign)
F. Increment and Decrement Operators: Increase or decrease the value of a variable by one.
++ (Increment)
-- (Decrement)
G. Ternary Operator: A shorthand way to write an if-else statement in a single line.
sizeof
I. Pointer Operators: Used with pointers for dereferencing and address retrieval.
* (Pointer dereference)
& (Address-of)
->
K. Comma Operator: Separate expressions within a larger expression and return the value of
the last expression.
,
L. Bitwise Shi Operators: Perform bitwise shi s to the le or right.
N. Condi onal Compila on Operator: Used in preprocessor direc ves for condi onal
compila on.
#include <stdio.h>
int main() {
double num1, num2;
if (num2 != 0) {
prin ("Division: %lf\n", num1 / num2);
} else {
prin ("Cannot divide by zero.\n");
}
return 0;
}
#include <stdio.h>
int main() {
int num1, num2;
return 0;
}
#include <stdio.h>
int main() {
int num;
return 0;
}
#include <stdio.h>
int main() {
int num;
return 0;
}
#include <stdio.h>
int main() {
int num;
num += 10;
return 0;
}
#include <stdio.h>
int main() {
int num;
prin ("Enter an integer: ");
scanf("%d", &num);
num++;
prin ("A er incremen ng: %d\n", num);
num--;
prin ("A er decremen ng: %d\n", num);
return 0;
}
#include <stdio.h>
int main() {
int num;
(num > 0) ? prin ("Posi ve\n") : ((num < 0) ? prin ("Nega ve\n") : prin ("Zero\n"));
return 0;
}
#include <stdio.h>
int main() {
int num;
prin ("Enter an integer: ");
scanf("%d", &num);
return 0;
}
#include <stdio.h>
int main() {
prin ("Size of int: %lu bytes\n", sizeof(int));
prin ("Size of char: %lu bytes\n", sizeof(char));
prin ("Size of float: %lu bytes\n", sizeof(float));
prin ("Size of double: %lu bytes\n", sizeof(double));
return 0;
}
#include <stdio.h>
int main() {
int a, b, c;
int result = (a + b) * c;
prin ("(%d + %d) * %d = %d\n", a, b, c, result);
return 0;
}
#include <stdio.h>
int main() {
prin ("Hello, World!\n");
return 0;
}
int main() {
int num1, num2;
return 0;
}
#include <stdio.h>
int main() {
double length, width;
return 0;
}
#include <stdio.h>
int main() {
double celsius, fahrenheit;
return 0;
}
#include <stdio.h>
int main() {
int num1, num2;
return 0;
}
#include <stdio.h>
int main() {
double principal, rate, me, interest;
#include <stdio.h>
int main() {
int num;
if (num % 2 == 0) {
prin ("%d is even.\n", num);
} else {
prin ("%d is odd.\n", num);
}
return 0;
}
#include <stdio.h>
int main() {
int num;
int factorial = 1;
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
return 0;
}
9. Problem: Generate Fibonacci Series
Problem Statement: Write a C program to generate the Fibonacci series up to a given
number of terms.
#include <stdio.h>
int main() {
int num_terms;
prin ("\n");
return 0;
}
#include <stdio.h>
int main() {
double base;
int exponent;
return 0;
}
Selection statements allow the programmer to decide based on a condition. The most
common selection statements in C are the if statement and the switch statement.
Loop statements allow the programmer to execute a block of statements repeatedly
until a condition is met. The most common loop statements in C are the for loop, the
while loop, and the do-while loop.
Jump statements allow the programmer to transfer control to a different part of the
program. The most common jump statements in C are the break, continue, and goto
statements.
Control structures are essential for writing efficient and readable C programs. They
allow the programmer to control the flow of execution clearly and easy to understand.
a. If Statements:
1. Program 1: Check Even or Odd
Problem: Write a program that takes an integer as input and prints whether it's even or
odd.
#include <stdio.h>
int main() {
int num;
if (num % 2 == 0) {
prin ("%d is even.\n", num);
} else {
prin ("%d is odd.\n", num);
}
return 0;
}
2. Program 2: Determine Leap Year
Problem: Write a program that checks if a given year is a leap year or not.
#include <stdio.h>
int main() {
int year;
return 0;
}
#include <stdio.h>
int main() {
int num1, num2, num3;
return 0;
}
4. Program 4: Check for Vowel or Consonant
Problem: Write a program that checks if a given character is a vowel or a consonant.
#include <stdio.h>
int main() {
char ch;
return 0;
}
#include <stdio.h>
int main() {
int num;
if (num > 0) {
prin ("%d is posi ve.\n", num);
} else if (num < 0) {
prin ("%d is nega ve.\n", num);
} else {
prin ("The number is zero.\n");
}
return 0;
}
b. If-Else Statements:
1. Program 1: Determine Greater Number
Problem: Write a program that takes two numbers as input and prints the greater one.
#include <stdio.h>
int main() {
int num1, num2;
return 0;
}
#include <stdio.h>
int main() {
int score;
return 0;
}
3. Program 3: Calculate Discount
Problem: Write a program that calculates the final price of an item a er applying a
discount based on its cost.
#include <stdio.h>
int main() {
float cost, discount, finalPrice;
return 0;
}
int main() {
int x, y;
return 0;
}
#include <stdio.h>
int main() {
float side1, side2, side3;
if (side1 + side2 > side3 && side2 + side3 > side1 && side3 + side1 > side2) {
prin ("It's a valid triangle.\n");
} else {
prin ("It's not a valid triangle.\n");
}
return 0;
}
c. Switch Statements:
1. Program 1: Menu-Driven Calculator
Problem: Write a program that implements a menu-driven calculator using a switch
statement.
#include <stdio.h>
int main() {
int choice;
float num1, num2, result;
switch (choice) {
case 1:
result = num1 + num2;
prin ("Sum: %.2f\n", result);
break;
case 2:
result = num1 - num2;
prin ("Difference: %.2f\n", result);
break;
case 3:
result = num1 * num2;
prin ("Product: %.2f\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
prin ("Quo ent: %.2f\n", result);
} else {
prin ("Division by zero is not allowed.\n");
}
break;
default:
prin ("Invalid choice!\n");
}
return 0;
}
#include <stdio.h>
int main() {
int day;
switch (day) {
case 1:
prin ("Sunday\n");
break;
case 2:
prin ("Monday\n");
break;
case 3:
prin ("Tuesday\n");
break;
case 4:
prin ("Wednesday\n");
break;
case 5:
prin ("Thursday\n");
break;
case 6:
prin ("Friday\n");
break;
case 7:
prin ("Saturday\n");
break;
default:
prin ("Invalid input! Please enter a number between 1 and 7.\n");
}
return 0;
}
#include <stdio.h>
int main() {
int score;
scanf("%d", &score);
case 10:
case 9:
break;
case 8:
break;
case 7:
break;
case 6:
break;
default:
prin ("Grade: F\n");
return 0;
#include <stdio.h>
int main() {
char ch;
switch (ch) {
case 'A':
case 'a':
prin ("ASCII value of %c is %d\n", ch, (int)ch);
break;
case 'Z':
case 'z':
prin ("ASCII value of %c is %d\n", ch, (int)ch);
break;
default:
prin ("Character %c is not 'A' or 'Z'.\n", ch);
}
return 0;
}
#include <stdio.h>
int main() {
int dayNumber;
switch (dayOfWeek) {
case 0:
prin ("Sunday\n");
break;
case 1:
prin ("Monday\n");
break;
case 2:
prin ("Tuesday\n");
break;
case 3:
prin ("Wednesday\n");
break;
case 4:
prin ("Thursday\n");
break;
case 5:
prin ("Friday\n");
break;
case 6:
prin ("Saturday\n");
break;
default:
prin ("Invalid day number.\n");
}
return 0;
}
d. For Loops:
1. Program 1: Print Numbers from 1 to N
Problem: Write a program that takes an integer N as input and prints all numbers from 1 to
N using a for loop.
#include <stdio.h>
int main() {
int N;
return 0;
}
2. Program 2: Calculate Sum of First N Natural Numbers
Problem: Write a program that calculates and prints the sum of the first N natural numbers
using a for loop.
#include <stdio.h>
int main() {
int N, sum = 0;
return 0;
}
#include <stdio.h>
int main() {
int num;
return 0;
}
#include <stdio.h>
int main() {
int N;
long long factorial = 1;
return 0;
}
#include <stdio.h>
int main() {
int num, isPrime = 1; // Assume the number is prime ini ally
if (num <= 1) {
isPrime = 0; // Numbers less than or equal to 1 are not prime
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0; // It's not prime if there's a factor
break;
}
}
}
if (isPrime) {
prin ("%d is a prime number.\n", num);
} else {
prin ("%d is not a prime number.\n", num);
}
return 0;
}
e. Nested For Loops:
1. Program 1: Print a Pa ern (Half Pyramid)
Problem: Write a program that prints a half pyramid pa ern of asterisks (*) using
nested for loops.
#include <stdio.h>
int main() {
int rows;
return 0;
}
#include <stdio.h>
int main() {
int rows;
return 0;
}
3. Program 3: Print a Pa ern (Right Triangle) Problem: Write a program that prints a
right triangle pa ern of asterisks (*) using nested for loops.
#include <stdio.h>
int main() {
int rows;
return 0;
}
#include <stdio.h>
int main() {
int rows;
return 0;
}
5. Program 5: Print a Pa ern (Diamond)
Problem: Write a program that prints a diamond pa ern of asterisks (*) using
nested for loops.
#include <stdio.h>
int main() {
int rows, spaces;
spaces = rows - 1;
spaces = 1;
for (int i = 1; i <= rows - 1; i++) {
for (int j = 1; j <= spaces; j++) {
prin (" "); // Print spaces
}
for (int k = 1; k <= 2 * (rows - i) - 1; k++) {
prin ("* "); // Print asterisks
}
prin ("\n");
spaces++;
}
return 0;
}
f. While and Do-While Loops:
1. Program 1: Sum of Digits using While Loop
Problem: Write a program that calculates the sum of the digits of a posi ve integer
using a while loop.
#include <stdio.h>
int main() {
int num, digit, sum = 0;
return 0;
}
#include <stdio.h>
int main() {
int num, reversedNum = 0, digit;
do {
digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
} while (num != 0);
return 0;
}
3. Program 3: Calculate Factorial using While Loop
Problem: Write a program that calculates and prints the factorial of a posi ve integer
using a while loop.
#include <stdio.h>
int main() {
int num, fact = 1, i = 1;
return 0;
}
#include <stdio.h>
int main() {
int terms, first = 0, second = 1, next, i = 0;
prin ("\n");
return 0;
}
int main() {
int num, originalNum, reversedNum = 0, digit;
originalNum = num;
do {
digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
} while (num != 0);
if (originalNum == reversedNum) {
prin ("%d is a palindrome.\n", originalNum);
} else {
prin ("%d is not a palindrome.\n", originalNum);
}
return 0;
}
g. Break Statements:
1. Program 1: Find Prime Numbers within a Range Problem: Write a program that finds
and prints prime numbers within a specified range using a for loop and the break
statement.
#include <stdio.h>
int main() {
int start, end;
if (num <= 1) {
isPrime = 0; // Numbers less than or equal to 1 are not prime
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0; // It's not prime if there's a factor
break; // Exit the inner loop.
}
}
}
if (isPrime) {
prin ("%d ", num);
}
}
prin ("\n");
return 0;
}
#include <stdio.h>
int main() {
int num;
while (1) {
scanf("%d", &num);
if (num < 0) {
break; // Exit the loop when a nega ve number is entered
}
return 0;
}
h. Goto Statements:
1. Program 1: Use Goto to Exit Loop
Problem: Write a program that demonstrates the use of the goto statement to exit
a loop when a specific condi on is met. In this case, exit the loop when the sum of
integers from 1 to n exceeds 100.
#include <stdio.h>
int main() {
int n, sum = 0, i = 1;
while (i <= n) {
sum += i;
if (sum > 100) {
goto exit_loop;
}
i++;
}
exit_loop:
prin ("Sum exceeded 100. Current sum: %d\n", sum);
return 0;
}
#include <stdio.h>
int main() {
prin ("Even numbers between 1 and 20 (skipping odd numbers):\n");
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0) {
con nue; // Skip odd numbers
}
prin ("%d\n", i);
}
return 0;
}
2. Program: Print Mul ples of 5
Problem Statement: Write a program that uses a loop to print all mul ples of 5
between 1 and 50, skipping numbers that are not mul ples of 5.
#include <stdio.h>
int main() {
prin ("Mul ples of 5 between 1 and 50:\n");
for (int i = 1; i <= 50; i++) {
if (i % 5 != 0) {
con nue; // Skip numbers that are not mul ples of 5
}
prin ("%d\n", i);
}
return 0;
}
#include <stdio.h>
int main() {
prin ("Even numbers between 1 and 20 (skipping odd numbers):\n");
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0) {
con nue; // Skip odd numbers
}
prin ("%d\n", i);
}
return 0;
}
#include <stdio.h>
int main() {
prin ("Numbers from 1 to 10 (skipping 3 and 7):\n");
for (int i = 1; i <= 10; i++) {
if (i == 3 || i == 7) {
con nue; // Skip numbers 3 and 7
}
prin ("%d\n", i);
}
return 0;
}
#include <stdio.h>
int main() {
int num;
while (1) {
scanf("%d", &num);
if (num == 0) {
break; // Exit the loop when the user enters 0
}
if (num < 0) {
con nue; // Skip nega ve numbers
}
return 0;
}
int main() {
int x = 5, y = 7;
int result = add(x, y); // Function call
printf("Sum: %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
In this example:
In OOP, data and the functions that operate on that data are grouped together into
objects, allowing for a more structured and modular approach to software development.
Here are some key concepts and principles of OOP:
OOP languages, such as C++, Java, Python, and C#, are designed to facilitate these
concepts and principles. Developers use classes and objects to model real-world entities
and solve problems in a way that mirrors the real world. OOP is widely used in software
development due to its ability to improve code organization, maintainability, and
reusability.
A. Basic Func on:
Program: A simple func on that adds two numbers and returns the result.
#include <stdio.h>
int main() {
int result = add(5, 7); // Func on call
prin ("Sum: %d\n", result);
return 0;
}
Explana on: This program defines a basic func on add that takes two integers as parameters
and returns their sum. The func on is called in the main func on, and the result is printed.
void greet() {
prin ("Hello, World!\n");
}
int main() {
greet(); // Func on call
return 0;
}
Explana on: This program defines a void func on greet that prints a gree ng message. The
func on is called in the main func on.
int main() {
float result = average(5.0, 7.5, 8.2); // Func on call
prin ("Average: %.2f\n", result);
return 0;
}
Explana on: This program defines a func on average that takes three floa ng-point numbers
as parameters and returns their average. The func on is called in the main func on.
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
int main() {
int result = factorial(5); // Func on call
prin ("Factorial: %d\n", result);
return 0;
}
Explana on: This program defines a recursive func on factorial that calculates the factorial
of a non-nega ve integer. The func on calls itself with a smaller argument un l it reaches
the base case.
E. Func on Pointer:
Program: A func on with default arguments to calculate the power of a number.
#include <stdio.h>
int main() {
double result1 = power(2.0, 3); // Func on call with specified exponent
double result2 = power(2.0, 2); // Default exponent is 2
prin ("Result 1: %.2f\n", result1);
prin ("Result 2: %.2f\n", result2);
return 0;
}
Explana on: This program defines a func on power to calculate the power of a number. It
uses a default exponent value of 2 if not specified.
F. Variadic Func on:
Variadic func ons are func ons that can take a variable number of arguments. In C
programming, a variadic func on adds flexibility to the program. It takes one fixed
argument and then any number of arguments can be passed.
Chapter-V: Array
An array in C is a data structure that allows you to store a collection of elements
of the same data type under a single variable name. Each element in an array is
identified by an index, and arrays provide an efficient way to store and access
multiple values of the same type in a contiguous block of memory. Arrays are
commonly used for tasks like storing lists of data, processing data in a structured
manner, and implementing data structures like matrices and vectors.
There are several types of arrays in C:
One-Dimensional Array: A one-dimensional array is a simple list of elements
of the same data type. Elements in a one-dimensional array are accessed using a
single index.
For example:
int numbers[5]; // An array of 5 integers
Two-Dimensional Array: A two-dimensional array is an array of arrays. It's used
to represent tables or matrices with rows and columns. Elements in a two-
dimensional array are accessed using two indices (row and column).
For example:
int matrix[3][3]; // A 3x3 integer matrix
Multi-Dimensional Array: C allows you to create arrays with more than two
dimensions, known as multi-dimensional arrays. These are used for applications
like representing 3D data or higher-dimensional data. Accessing elements
requires specifying multiple indices.
For example:
int cube[2][3][4]; // A 3D array
Character Array (String): A character array is a one-dimensional array of
characters. It is commonly used to store and manipulate strings in C. Strings in C
are null-terminated, meaning they end with a null character '\0'.
For example:
char name[20]; // A character array to store a name
Dynamic Array: In C, arrays have a fixed size determined at compile time.
However, dynamic arrays are implemented using pointers and dynamic memory
allocation functions like malloc() and realloc(). These arrays can grow or shrink
during runtime as needed.
For example:
int* dynamicArray = NULL; // Dynamic array of integers
Jagged Array (Array of Pointers): A jagged array is an array in which each
element is itself an array. Unlike a true two-dimensional array, the sub-arrays can
have different lengths.
For example:
int* rows[3]; // An array of integer pointers, creating a jagged array
int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Explanation: In this program, we initialize an array of integers and find the
maximum element by iterating through the array. We start by assuming that the
first element is the maximum and compare it with the other elements. If we find
an element greater than the current maximum, we update the maximum.
Practice 01: Do the above program to get the user input for the array element
count and the element also from the user :
#include <stdio.h>
int main() {
int n;
int arr[n];
int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return 0;
}
Explanation: This program calculates the sum of array elements by iterating
through the array and adding each element to the sum variable.
int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int start = 0;
int end = n - 1;
int temp;
return 0;
}
Explanation: In this program, we reverse an array by using two pointers (start
and end) that initially point to the first and last elements of the array, respectively.
We swap elements at these indices and move the pointers inward until they meet
in the middle of the array.
int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return 0;
}
Explanation: This program calculates the average of array elements by first
finding the sum of elements and then dividing it by the number of elements (n).
We cast the sum to a float to ensure accurate floating-point division.
int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int evenCount = 0;
int oddCount = 0;
return 0;
}
Explanation: This program counts the number of even and odd elements in an
array by iterating through the array and checking the remainder when each
element is divided by 2. If the remainder is 0, the element is even; otherwise, it's
odd.
Matrix Multiplication:
Problem 6: Matrix Multiplication
Problem Statement: Write a C program to multiply matrix of user defined matrix
Solution:
#include <stdio.h>
int main() {
int m, n, p, q;
// Input the dimensions of the first matrix (m x n)
printf("Enter the dimensions of the first matrix (m x n): ");
scanf("%d %d", &m, &n);
// Declare arrays for the two input matrices and the result matrix
int mat1[m][n], mat2[p][q], result[m][q];
// Perform matrix multiplication Here there is no need of 'p' --> Row of 2nd Matrix.
int main() {
int rows, cols;
int matrix[rows][cols];
return 0;
}
Explanation: In this program, the user specifies the number of rows and columns
for a 2D numeric array. We use nested for loops to input and display the elements
of the 2D array. This example demonstrates the use of a 2D numeric array to
organize and display tabular data.
int main() {
int numbers[5] = {10, 5, 8, 3, 12};
int size = 5;
return 0;
}
int main() {
int rows, cols;
int matrix[rows][cols];
int sum = 0;
return 0;
}
Explanation: In this program, the user is prompted to input the dimensions of a
2D array (number of rows and columns) and then fill the array with values.
Afterward, the program calculates and displays the sum of all elements in the
array.
int main() {
int rows = 4, cols = 4;
int matrix[4][4] = {
{25, 10, 5, 15},
{40, 20, 30, 35},
{60, 55, 50, 45},
{75, 70, 65, 80}
};
return 0;
}
Explanation: This program initializes a 2D array with random values, sorts it in
ascending order using Bubble Sort, and then displays the sorted array.
int main() {
int rowsA = 3, colsA = 2;
int rowsB = 2, colsB = 3;
int matrixA[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int matrixB[2][3] = {{7, 8, 9}, {10, 11, 12}};
int result[3][3] = {0};
return 0;
}
Explanation: This program multiplies two 2D arrays and stores the result in a
third array. It demonstrates the concept of matrix multiplication.
Program 12: 2D Array Transposition
Problem Statement: Create a C program that transposes a given 2D array,
switching rows and columns.
#include <stdio.h>
int main() {
int rows = 3, cols = 4;
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int transpose[4][3];
// Transpose the matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
return 0;
}
Explanation: This program transposes a 2D array, interchanging rows and
columns, and then displays the transposed array.
int main() {
int rows = 3, cols = 4;
int matrix[3][4] = {
{45, 12, 76, 23},
{89, 54, 32, 67},
{14, 98, 43, 56}
};
int largest = matrix[0][0];
return 0;
}
Explanation: This program finds and displays the largest element in a 2D array.
It demonstrates how to iterate through a 2D array and track the largest element.
Chapter-VI: Syntax Error
Identify and rectify the following syntax error in the given program.
1. if (x > 10
{
printf("x is greater than 10");
}
Solution: The syntax error in this code is a missing closing parenthesis ) in
the if statement condition. It should be if (x > 10).
2. if (condition) {
printf("Condition is true");
} else
{
printf("Condition is false");
Solution: The syntax error in this code is inconsistent formatting. The
opening brace of the else block should be on the same line as else. It should
be } else {.
3. int count = 0;
while (count < 5)
{
printf("Count is %d\n", count);
count++;
Solution: The syntax error in this code is a missing closing brace } for the
while loop. It should be } after count++;.
4. int i = 0;
do {
printf("Value of i is %d\n", i);
} while (i < 5);
Solution: The syntax error in this code is that there's no semicolon ; at the
end of the do-while loop. It should be } while (i < 5);.
5. for (int i = 0; i < 10; i++)
{
printf("Value of i: %d\n", i);
}
Solution: There is no syntax error in this code; it's a correct usage of the for
loop.
6. goto jump;
printf("This code is unreachable\n");
jump:
printf("Jumped to this label");
Solution: The syntax error in this code is that goto statements are not
followed by a semicolon. It should be goto jump; instead of goto jump;.
7. int choice = 2;
switch (choice)
{
case 1:
printf("Choice 1");
case 2:
printf("Choice 2");
case 3:
printf("Choice 3");
}
Solution: There is no syntax error in this code; it's a correct usage of the
switch statement. However, it lacks break statements, which might lead to
unintended fall-through behaviours.
8. int add(int a, b)
{
return a + b;
}
Solution: The syntax error in this code is missing the data type for the second
parameter b in the function declaration. It should be int add(int a, int b).
9. int numbers[5;
Solution: The syntax error in this code is a missing closing square bracket ]
in the array declaration. It should be int numbers[5];.
[Link] values[3];
int x = values[3];
Solution: The syntax error in this code is trying to access an array element
at an out-of-bounds index. The array values have indices 0, 1, and 2, but
we're trying to access index 3, which is out of range. It should be within the
valid index range (0 to 2).
[Link] multiply(int x, y) {
return x * y;
}
Solution: The syntax error in this code is missing data types for both
parameters in the function definition. It should be int multiply(int x, int y).
[Link] vowels[] = {'a', 'e', 'i', 'o' 'u'};
Solution: The syntax error in this code is a missing comma , between the
characters 'o' and 'u' in the array initialization. It should be {'a', 'e', 'i',
'o', 'u'}.
[Link] x = 5
Solution: The syntax error in this code is a missing semicolon ; at the end
of the statement. It should be int x = 5;.
[Link] 123abc = 42;
Solution: The syntax error in this code is using an invalid identifier
(variable name). Variable names cannot start with a digit. It should be
something like int abc123 = 42;.
15.#include <stdio>
int main() {
printf("Hello, World!");
return 0;
}
Solution: The syntax error in this code is an incorrect use of the #include
directive. The <stdio.h> header file should have .h, like this: #include
<stdio.h>.
Chapter-VII: String
Strings in C Programming:
Definition:
Character Arrays: Strings in C are represented as arrays of characters. Each
element in the array holds a character, and the sequence of characters forms
the string.
Null Termination: C strings are null terminated, meaning they end with a
special character called the null character ('\0'). The null character marks
the end of the string.
Types of Strings:
String Literals: Strings can be defined using string literals, enclosed in
double quotes. For example: "Hello, World!".
int main() {
char myString[] = "Hello";
int length = strlen(myString);
printf("Length of the string: %d\n", length);
return 0;
}
2. String Copy:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Copy this string!";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
char source[] = "Copy this string!";: Declares a character array source
and initializes it with the string.
char destination[20];: Declares an empty character array destination with
enough space to hold the copied string.
strcpy(destination, source);: Uses the strcpy function to copy the
contents of source to destination.
printf("Copied string: %s\n", destination);: Prints the copied string.
3. String Concatenation:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
char str1[20] = "Hello, ";: Declares a character array str1 and initializes
it with the string "Hello, ".
char str2[] = "World!";: Declares a character array str2 and initializes it
with the string "World!".
strcat(str1, str2);: Uses the strcat function to concatenate str2 to the end
of str1.
printf("Concatenated string: %s\n", str1);: Prints the concatenated
string.
4. String Reversal:
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Reverse This!";
strrev(text);
printf("Reversed string: %s\n", text);
return 0;
}
char text[] = "Reverse This!";: Declares a character array text and
initializes it with the string "Reverse This!".
strrev(text);: Uses the strrev function to reverse the characters in text in-
place.
printf("Reversed string: %s\n", text);: Prints the reversed string.
5. String Comparison:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "orange";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
return 0;
}
char str1[] = "apple";: Declares a character array str1 and initializes it
with the string "apple".
char str2[] = "orange";: Declares a character array str2 and initializes it
with the string "orange".
strcmp(str1, str2) == 0: Uses the strcmp function to compare str1 and
str2. If the result is 0, it means the strings are equal.
The program then prints whether the strings are equal or not based on the
comparison result.
These examples demonstrate common string operations in C, utilizing
functions from the <string.h> library. They cover finding the length,
copying, concatenating, reversing, and comparing strings.
Addi onal problem in s ngs in C programming:
Solu on:
#include <stdio.h>
int main() {
char myString[] = "Assignment";
int length = stringLength(myString);
prin ("Length of the string: %d\n", length);
return 0;
}
Explana on:
The program defines a func on stringLength to find the length of a string using a loop un l
the null character is encountered.
Solu on:
#include <stdio.h>
int main() {
char source[] = "Copy Assignment";
char des na on[20];
stringCopy(des na on, source);
prin ("Copied string: %s\n", des na on);
return 0;
}
Explana on:
The program defines a func on stringCopy to copy characters from one string to another
using a loop.
Solu on:
#include <stdio.h>
int i = 0;
while (src[i] != '\0') {
dest[destLen + i] = src[i];
i++;
}
dest[destLen + i] = '\0';
}
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
stringConcat(str1, str2);
prin ("Concatenated string: %s\n", str1);
return 0;
}
Explana on:
The program defines a func on stringConcat to concatenate two strings without using the
strcat func on.
4. Palindrome Check
Problem:
Write a program to check if a given string is a palindrome.
Solu on:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main() {
char myString[] = "madam";
if (isPalindrome(myString)) {
prin ("The string is a palindrome.\n");
} else {
prin ("The string is not a palindrome.\n");
}
return 0;
}
Explana on:
The program defines a func on is Palindrome to check if a string is a palindrome by
comparing characters from both ends.
Solu on:
#include <stdio.h>
#include <ctype.h>
int main() {
char myString[] = "Count Vowels and Consonants";
int numVowels, numConsonants;
countVowelsConsonants(myString, &numVowels, &numConsonants);
Explana on:
The program defines a func on countVowelsConsonants to count the number of vowels and
consonants in a string.
6. Remove Spaces
Problem:
Write a program to remove spaces from a given string.
Solu on:
#include <stdio.h>
int main() {
char myString[] = "Remove Spaces from String";
removeSpaces(myString);
prin ("String without spaces: %s\n", myString);
return 0;
}
Explana on:
The program defines a func on removeSpaces to remove spaces from a string by shi ing
characters.
7. Word Count
Problem:
Write a program to count the number of words in a given string.
Solu on:
#include <stdio.h>
return words;
}
int main() {
char myString[] = "Count the Words in This String";
int numWords = countWords(myString);
prin ("Number of words: %d\n", numWords);
return 0;
}
Explana on:
The program defines a func on countWords to count the number of words in a string.
Structure in C
[Link]
structure in C programs
A structure is a user-defined data type that allows us to
group different data types under a single name.
Structures are used to represent a collection of related
variables, possibly of different types, under a single
name. The variables within a structure are called
members.
What are Data
Structures?
Data structures are specialized formats for organizing, processing, and
storing data. They enable efficient data access and modification, which
are critical for the performance of software applications. In essence,
data structures are containers that hold data in a specific layout,
allowing for easy manipulation and retrieval.
c<br />struct Book {<br /> char title[50];<br /> char author[50];<br /> int pages;<br /> float price;<br />};<br />
This structure named 'Book' contains four members: 'title', 'author', 'pages', and 'price'.
Basic syntax for declaring a structure in C:…
We can declare variables of the structure type and access its members using
the dot (.) operator:
struct Point p1; // Declare a variable of type Point
// Access and assign values to members Once a structure is defined, we can declare variables of that
type. For example, using the 'Book' structure defined
p1.x = 10; previously:
p1.y = 20; c<br />struct Book myBook;<br />
This declares a variable 'myBook' of type 'struct Book'.
We can also use pointers to structures. Here's an example using the 'Book'
structure:
c<br />struct Book *ptrBook;<br />ptrBook = &myBook;<br />printf("Title:
%s\n", ptrBook->title);<br />
Here, 'ptrBook' is a pointer to a 'Book' structure, and 'ptrBook->title'
accesses the 'title' member of the structure pointed to by 'ptrBook'.
Structure within a Structures:
Structures can be nested within other structures. For example, if you wanted
to store information about a library, you could define a structure like this:
c<br />struct Library {<br /> struct Book collection[100];<br /> int
totalBooks;<br />};<br />
Here, the 'Library' structure contains an array of 'Book' structures and an
integer 'totalBooks' to keep track of the number of books.
Nested Structures: (cont…)
Structures can be nested inside other structures to create more complex data structures:
struct Address {
char street[50];
char city[50];
char state[20];
};
struct Person {
char name[50];
int age;
struct Address address; // Nested structure
};
Passing Structures to Functions:
We can pass structures to functions by value or by reference (using pointers):
// Pass by value
void displayPerson(struct Person p) {
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
}
// Pass by reference
void updateAge(struct Person *p, int newAge) {
p->age = newAge; // Using arrow operator to access members through a
pointer
}
Arrays of Structures:
We can create arrays of structures to store multiple instances of the same structure type:
struct Student {
char name[50];
int age;
float gpa;
};
// Define a structure
typedef struct Point {
int x;
int y;
} Point;
int main() {
// Create a Point structure
Point point1 = {1, 2};
return 0;
}
Explana on:
This program demonstrates that call by value creates a copy of the argument, while call by reference
modifies the original argument directly. Choosing between call by value and call by reference
depends on the specific needs of your program.
// Define a structure
typedef struct Point {
int x;
int y;
} Point;
int main() {
// Create two Point structures
Point point1 = {1, 2};
Point point2 = {3, 4};
return 0;
}
Explana on:
This program defines a Point structure and a func on swapPointsByValue that takes two Point
structures as arguments.
The swapPointsByValue func on creates copies of the argument structures and stores them in
temporary variables.
It then swaps the values of the temporary variables.
However, since the func on only receives copies of the original structures, any changes made
within the func on are not reflected in the original structures.
Therefore, prin ng the original point1 and point2 a er the func on call will show their original
values.
// Define a structure
typedef struct Point {
int x;
int y;
} Point;
int main() {
// Create two Point structures
Point point1 = {1, 2};
Point point2 = {3, 4};
return 0;
}
Explana on:
This program uses pointers to pass Point structures to the swapPointsByReference func on.
Inside the func on, the * operator dereferences the pointers to access the actual structures.
Swapping the values of the dereferenced pointers directly modifies the original structures.
Therefore, prin ng the original point1 and point2 a er the func on call will show their swapped
values.
Understanding Pointers in C Programming
Focusing on Pointers fundamental concepts, memory allocation, and their usage in functions.
Pointers are a powerful feature in C that allows for direct memory manipulation, making them
essential for efficient programming. This guide is tailored for first-time learners, complete
with examples to illustrate each concept clearly.
Pointers are variables that store the memory address of another variable. They are declared
using the asterisk (*) symbol. Understanding pointers is crucial for dynamic memory
management and efficient data handling in C.
To declare a pointer, We specify the type of data it will point to, followed by an asterisk and
the pointer's name. For example:
We can initialize a pointer by assigning it the address of a variable using the address-of
operator (&):
To access the value stored at the address a pointer points to, We use the dereference
operator (*). For example:
Dynamic memory allocation in C is done using pointers. The malloc, calloc, realloc, and free
functions from the stdlib.h library are used for this purpose.
Using `malloc`
The malloc function allocates a specified number of bytes and returns a pointer to the
allocated memory. Here's an example:
int main() {
int *arr;
int n = 5;
Allocate
memory for an Initialize and
array print the array
Using `calloc`
The calloc function allocates memory for an array and initializes all bytes to zero:
arr = (int*)calloc(n, sizeof(int)); // Allocates memory for n integers and
initializes to 0
Using `realloc`
Freeing Memory
Always free dynamically allocated memory using the free function to prevent memory leaks:
free(arr);
Pointers in Functions
Pointers can be used to pass variables to functions by reference, allowing the function to
modify the original variable.
Passing by Reference
#include <stdio.h>
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y); // Passing addresses of x and y
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
Returning Pointers from Functions
We can also return pointers from functions. However, be cautious about returning pointers to
local variables, as they will be destroyed once the function exits.
Pros Cons
Dynamic Risk of
memory dangling
allocation pointers
Flexible array
Memory leaks
size
Efficient Complex
memory memory
usage management
Conclusion
// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;
int main()
{
// Define the String
char str[100] = "GeeksforGeeks";
// Driver Code
int main()
{
int arr[] = {8, 9, 0, 1, 2, 0, 3};
int n = sizeof(arr) / sizeof(arr[0]);
moveZerosToEnd(arr, n);
printf("\nModified array: ");
printArray(arr, n);
return 0;
}
struct name {
member1;
member2;
};
int main()
#include <stdio.h>
struct person
int age;
float weight;
};
int main()
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
return 0;
In this example, the address of person1 is stored in the personPtr pointer using personPtr =
&person1;.
Now, you can access the members of person1 using the personPtr pointer.
Sometimes, the number of struct variables we declared may be insu icient. we may need
to allocate memory during run-time. Here's how we can achieve this in C programming.
#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
char name[30];
};
int main()
int i, n;
printf("Enter the number of persons: ");
scanf("%d", &n);
printf("Displaying Information:\n");
return 0;
In the above example, n number of struct variables are created where n is entered by the
user.
#include <stdio.h>
#include <stdlib.h>
int main() {
scanf("%d", &n);
if(ptr == NULL) {
exit(0);
free(ptr);
return 0;
Expected output:
20
36
Sum = 156
#include <stdio.h>
#include <stdlib.h>
int main() {
scanf("%d", &n);
if(ptr == NULL) {
exit(0);
free(ptr);
return 0;
Output:
20
36
Sum = 156
Example: realloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
scanf("%d", &n1);
printf("%pc\n",ptr + i);
scanf("%d", &n2);
// rellocating the memory
free(ptr);
return 0;
Output:
Enter size: 2
26855472
26855476
26855472
26855476
26855480
26855484
File handling in C
Programming
[Link]
Assistant Professor (Senior Grade)
Dept of Mechanical Engineering
ASE-AMRITA VISHWA VIDYAPEETHAM
Coimbatore.
File Handling in C:
In order to understand why file handling is important, let us look at a few features of using files:
• Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime
providing high reusability.
• Portability: Without losing any data, files can be transferred to another in the computer system. The risk of
flawed coding is minimized with this feature.
• Efficient: A large amount of input may be required for some programs. File handling allows you to easily
access a part of a file using few instructions which saves a lot of time and reduces the chance of errors.
• Storage Capacity: Files allow you to store a large amount of data without having to worry about storing
everything simultaneously in a program.
Types of Files in C
1. Printing a CAR
#include <stdio.h>
int main() {
printf("| _| _ | \n");
printf(" () | | () \n");
return 0;
Explanation:
1. #include <stdio.h>: This line includes the Standard Input Output header file which is nec
essary for using printf function.
2. int main() {: The main function where the program execution starts.
3. printf(" _______ \n");: Prints the top part of the car. \n is used to move to the next line.
4. printf(" ____/ \\____ \n");: Prints the roof and windows of the car.
Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. int main() {: The main function where the program execution starts.
3. int i, j, rows = 5;: Declares variables for loops and the number of rows.
4. for(i = 1; i <= rows; i++) {: Outer loop to iterate through each row.
5. for(j = i; j < rows; j++) { printf(" "); }: Prints spaces to align the stars in a pyramid shape.
6. for(j = 1; j <= (2 * i - 1); j++) { printf("*"); }: Prints stars for the pyramid pattern.
7. printf("\n");: Moves to the next line after printing each row.
8. return 0;: Indicates that the program executed successfully.
int main() {
int n = 5; // Number of rows in Pascal's Triangle
printPascal(n);
return 0;
}
Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. void printPascal(int n) {: Function to print Pascal's Triangle up to n rows.
3. int arr[n][n];: Declares a 2D array to hold the values of Pascal's Triangle.
4. for (int line = 0; line < n; line++) {: Outer loop to handle the number of rows.
5. for (int i = 0; i <= line; i++) {: Inner loop to handle the values in each row.
6. if (line == i || i == 0) { arr[line][i] = 1; }: Sets the first and last values of each row to 1.
7. else { arr[line][i] = arr[line-1][i-1] + arr[line-
1][i]; }: Calculates the other values as the sum of the values just above and to the left of
above.
8. printf("%d ", arr[line][i]);: Prints each value in the row.
9. printf("\n");: Moves to the next line after printing a row.
10. int main() { int n = 5; printPascal(n); return 0; }: Main function to call printPascal with 5 ro
ws.
#include <stdio.h>
if (filePtr == NULL) {
printf("Failed to create the file.\n");
return;
}
int arr[n][n];
for (int line = 0; line < n; line++) {
for (int i = 0; i <= line; i++) {
// The first and last values in every row are 1
if (line == i || i == 0) {
arr[line][i] = 1;
} else {
// Other values are the sum of values just above and left of above
arr[line][i] = arr[line-1][i-1] + arr[line-1][i];
}
// Print to console
printf("%d ", arr[line][i]);
// Write to file
fprintf(filePtr, "%d ", arr[line][i]);
}
printf("\n");
fprintf(filePtr, "\n");
}
fclose(filePtr);
}
if (filePtr == NULL) {
printf("Failed to open the file.\n");
return;
}
fclose(filePtr);
}
int main() {
int n = 5; // Number of rows in Pascal's Triangle
return 0;
}
Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. void printPascal(int n) {: Function to generate Pascal's Triangle and write it to a file.
3. FILE *filePtr; filePtr = fopen("[Link]", "w");: Opens (or creates) the file "[Link]" in
write mode.
4. int arr[n][n];: Declares a 2D array to hold the values of Pascal's Triangle.
5. Nested loops to generate Pascal's Triangle, print to the console, and write to the file.
6. fclose(filePtr);: Closes the file after writing.
7. void readAndDisplayFile() {: Function to read from the file and display the content.
8. filePtr = fopen("[Link]", "r");: Opens the file "[Link]" in read mode.
9. while ((ch = fgetc(filePtr)) != EOF) { putchar(ch); }: Reads characters from the file and prin
ts them to the console.
10. fclose(filePtr);: Closes the file after reading.
11. int main() { int n = 5; printPascal(n); readAndDisplayFile(); return 0; }: Main function to cal
l printPascal and readAndDisplayFile.
5. User input alphabet pyramid pattern printing infinity:
#include <stdio.h>
int main() {
char alphabet = 'A';
int i, j, rows;
return 0;
}
Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. char alphabet = 'A';: Declares a variable to store the starting alphabet character.
3. printf("Enter the number of rows: "); scanf("%d", &rows);: Prompts the user to enter the n
umber of rows for the pyramid.
4. Nested loops to generate the pyramid:
First loop: Prints spaces for alignment.
Second loop: Prints the alphabets for each row.
5. printf("\n");: Moves to the next line after printing each row.