C Programming [BESCK24104D/204/D]
MODULE 5
Strings: String taxonomy, operations on strings, Miscellaneous string and character
functions, arrays of strings.
Pointers: Understanding the Computers Memory, Introduction to Pointers, Declaring
Pointer Variables
Structures: Introduction to structures.
String Taxonomy
String Handling Functions in C
a) strcat()
Definition: The strcat() function concatenates (appends) one string to the end of another.
Syntax:
• dest: The destination string to which src will be appended.
• src: The source string to append
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
Dr. Ruma Sinha
printf("Concatenated String: %s\n", str1);
return 0;
}
String handling functions in C allow efficient manipulation of strings. These functions are
defined in the <string.h>header file. Below are explanations and examples of some commonly
used string handling functions:
b) strcpy()
Definition: The strcpy() function copies the content of one string into another.
Syntax:
• dest: The destination string where src will be copied.
• src: The source string to copy.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50];
char str2[] = "Copy this string.";
strcpy(str1, str2);
printf("Copied String: %s\n", str1);
return 0;
}
Output:
c) strcmp()
Definition: The strcmp() function compares two strings lexicographically.
Syntax:
int strcmp(const char *str1, const char *str2);
Returns:
• 0 if both strings are equal.
• A negative value if str1 is less than str2.
• A positive value if str1 is greater than str2.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
Dr. Ruma Sinha
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal.\n");
}
else {
printf("str1 is not equal to str2.\n");
}
return 0;
}
Output
str1 is not equal to str2.
d) strlen()
The strlen() function in C is used to calculate the length of a string (number of characters in the
string excluding the null-terminator \0). It is defined in the <string.h> library.
Syntax:
size_t strlen(const char *str);
• Parameter:
str - A pointer to the string whose length is to be calculated.
• Return Value: The function returns the length of the string as a size_t type.
Example Program:
#include <stdio.h>
#include <string.h>
int main() {
char string[] = "Hello, world!";
printf("Length: %zu\n", strlen(string));
return 0;
}
Output: Length: 13
Dr. Ruma Sinha
Write a C program to find length of a string without using library function.
Program:
#include <stdio.h>
int main() {
char str[100];
int length = 0;
// Input the string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Calculate the length of the string
while (str[length] != '\0' && str[length] != '\n') {
length++;
}
printf("The length of the string is: %d\n", length);
return 0;
}
Output:
Enter a string: This is a string
The length of the string is: 16
Write a C program to input a string, convert lowercase letters to uppercase
and vice versa without using library functions.
Program:
#include <stdio.h>
int main() {
char str[100];
int i;
// Input a string from the user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Convert lowercase to uppercase and vice versa
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
// Convert lowercase to uppercase
str[i] = str[i] - 'a' + 'A';
} else if (str[i] >= 'A' && str[i] <= 'Z') {
Dr. Ruma Sinha
// Convert uppercase to lowercase
str[i] = str[i] - 'A' + 'a';
}
}
// Output the modified string
printf("Converted string: %s\n", str);
return 0;
}
Output:
Enter a string: Global Academy of Technology
Converted string: gLOBAL aCADEMY OF tECHNOLOGY
Write a C program to count total number of vowels and consonants in a
string
Program:
#include <stdio.h>
int main() {
char str[100];
int i, vowels = 0, consonants = 0;
// Input a string from the user
printf("Enter a string: ");
scanf("%[^\n]", str); // Read a string including spaces until a newline
// Traverse through the string
for (i = 0; str[i] != '\0'; i++) {
// Check if the character is a letter
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
// Check for vowels
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
vowels++;
} else {
consonants++;
}
}
}
// Output the counts
printf("Total vowels: %d\n", vowels);
printf("Total consonants: %d\n", consonants);
return 0;
}
Dr. Ruma Sinha
Output:
Enter a string: Global Academy of Technology
Total vowels: 9
Total consonants: 16
Write a C program to count number of vowels, digits, blank space and
special characters from the given string.
Program:
#include <stdio.h>
int main() {
char str[100];
int i, vowels = 0, digits = 0, spaces = 0, special = 0;
// Input a string from the user
printf("Enter a string: ");
scanf("%[^\n]", str); // Read a string including spaces until a newline
// Traverse through the string
for (i = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
// Check for vowels
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
vowels++;
}
} else if (str[i] >= '0' && str[i] <= '9') {
// Check for digits
digits++;
} else if (str[i] == ' ') {
// Check for blank spaces
spaces++;
} else {
// Special characters
special++;
}
}
// Output the counts
printf("Total vowels: %d\n", vowels);
printf("Total digits: %d\n", digits);
printf("Total blank spaces: %d\n", spaces);
printf("Total special characters: %d\n", special);
return 0;
}
Dr. Ruma Sinha
Output:
Enter a string: Hello friends! How are you doing? Today is Jan 19 2025.
Total vowels: 15
Total digits: 6
Total blank spaces: 10
Total special characters: 3
Write a C program to check whether the given string is palindrome or not without using
Library functions.
Program:
#include <stdio.h>
int main() {
char str[100];
int i, length = 0, isPalindrome = 1;
// Input the string
printf("Enter a string: ");
scanf("%s", str);
// Calculate the length of the string manually
while (str[length] != '\0') {
length++;
}
// Check if the string is a palindrome
for (i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1]) {
isPalindrome = 0; // Not a palindrome
break;
}
}
// Output the result
if (isPalindrome) {
printf("The given string is a palindrome.\n");
} else {
printf("The given string is not a palindrome.\n");
}
return 0;
}
Output:
Sample 1:
Enter a string: madam
The given string is a palindrome.
Dr. Ruma Sinha
Sample 2:
Enter a string: Global
The given string is not a palindrome.
Write a C program to count the number of lines, words and characters in a given text.
Program:
#include <stdio.h>
int main() {
char text[1000];
int i, lines = 0, words = 0, characters = 0;
int inWord = 0;
// Input the text from the user
printf("Enter the text (end input with ~):\n");
scanf("%[^~]", text); // Read the input until the '~' character
// Traverse the text
for (i = 0; text[i] != '\0'; i++) {
characters++; // Count each character
if (text[i] == '\n') {
lines++; // Count lines
}
// Check for word boundaries
if (text[i] == ' ' || text[i] == '\n' || text[i] == '\t') {
if (inWord) {
words++;
inWord = 0; // End of a word
}
} else {
inWord = 1; // Inside a word
}
}
// If the last character is part of a word
if (inWord) {
words++;
}
// Add one line if the text is not empty
if (characters > 0) {
lines++;
}
// Output the results
Dr. Ruma Sinha
printf("Number of characters: %d\n", characters);
printf("Number of words: %d\n", words);
printf("Number of lines: %d\n", lines);
return 0;
}
Output:
Enter the text (end input with ~):
What should I enter?
Enough for now~
Number of characters: 35
Number of words: 7
Number of lines: 2
Write a C program to reverse a given string without using a library function.
Program:
#include <stdio.h>
int main() {
char str[100], temp;
int i, length = 0;
// Input the string
printf("Enter a string: ");
scanf("%s", str);
// Calculate the length of the string
while (str[length] != '\0') {
length++;
}
// Reverse the string in place
for (i = 0; i < length / 2; i++) {
temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
// Output the reversed string
printf("Reversed string: %s\n", str);
return 0;
}
Output:
Enter a string: DEVIL
Reversed string: LIVED
Dr. Ruma Sinha
Pointer in C
A pointer in C is a variable that stores the memory address of another variable. Pointers are a
powerful feature of C that enable direct access and manipulation of memory.
Syntax:
data_type *pointer_name;
• data_type specifies the type of data the pointer will point to.
• * is used to declare a pointer.
• pointer_name is the name of the pointer variable.
Significance of Pointers
• Direct Memory Access:
Pointers provide a way to access and manipulate memory directly, which is essential
for low-level programming tasks like working with hardware or managing memory.
• Efficient Memory Usage:
Pointers allow dynamic memory allocation using functions like malloc and free,
making programs more flexible and efficient.
• Pass by Reference:
When a pointer to a variable is passed to a function, the function can modify the original
variable. This avoids copying large data structures and allows direct changes.
• Array and String Handling:
Pointers can be used to traverse arrays or strings efficiently without needing additional
indexing.
• Dynamic Data Structures:
Data structures like linked lists, trees, and graphs rely on pointers to dynamically link
nodes and elements.
• Function Pointers:
Pointers can store the address of a function, enabling the creation of callback functions
and dynamic function calls.
Example: Basic Pointer Usage
#include <stdio.h>
int main() {
int a = 10; // A regular integer variable
int *ptr = &a; // Pointer to the variable 'a'
printf("Value of a: %d\n", a); // Direct access
printf("Address of a: %p\n", &a); // Memory address of 'a'
printf("Value of ptr: %p\n", ptr); // Pointer stores address of 'a'
printf("Value at ptr: %d\n", *ptr); // Dereferencing pointer to get value of 'a'
*ptr = 20; // Modifying 'a' via pointer
printf("New value of a: %d\n", a);
Dr. Ruma Sinha
return 0;
}
Output:
Value of a: 10
Address of a: 0x7ffee9ba3d94
Value of ptr: 0x7ffee9ba3d94
Value at ptr: 10
New value of a: 20
Relationship Between Pointers and Memory Addresses
• A memory address is a unique identifier for a specific memory location.
• A pointer is a variable that stores this memory address.
• Pointers are the bridge between variable values and their memory storage, enabling
direct memory manipulation, dynamic allocation, and efficient data access.
Advantages of Using Pointers in C Programming
• Dynamic memory allocation: allocate memory at runtime using malloc, calloc, etc.
• Pass by reference: pass variables to functions without copying them, enabling
modification of the original value.
• Efficient array and string handling: access array elements without explicit indexing.
• Data structures: build complex data structures like linked lists, trees, and graphs.
• Access to Hardware and Low-Level Programming: Pointers enable direct
manipulation of memory addresses, which is crucial for systems programming,
embedded systems, and hardware interactions.
Declaring a Pointer Variable in C
A pointer variable is declared by specifying the data type of the variable it will point to,
followed by an asterisk (*), and then the pointer's name.
Syntax
data_type *pointer_name;
• data_type: The type of data the pointer will point to (e.g., int, float, char, etc.).
• *: Indicates that the variable is a pointer.
• pointer_name: The name of the pointer variable.
Example to Declare and Assign a Pointer:
#include <stdio.h>
int main() {
int a = 10; // Declare an integer variable
int *ptr = &a; // Declare a pointer to an integer and assign the address of 'a'
printf("Value of a: %d\n", a); // Prints the value of 'a'
printf("Address of a: %p\n", &a); // Prints the address of 'a'
Dr. Ruma Sinha
printf("Pointer ptr points to: %p\n", ptr); // Prints the address stored in 'ptr'
printf("Value at ptr: %d\n", *ptr); // Dereferences 'ptr' to print the value of 'a'
return 0;
}
Explanation
1. int a = 10;
o Declares an integer variable a with a value of 10.
2. int *ptr = &a;
o Declares a pointer ptr that can hold the address of an integer.
o Assigns the address of a to ptr using the address-of operator (&).
3. Accessing Values and Addresses:
o &a: The address of variable a.
o ptr: The pointer ptr holds the memory address of a.
o *ptr: Dereferences the pointer ptr to get the value stored at the memory address
it points to.
Output:
Value of a: 10
Address of a: 0x7ffee9d3babc // Memory address (example)
Pointer ptr points to: 0x7ffee9d3babc
Value at ptr: 10
Initializing a Pointer with the Address of a Variable
Steps to Initialize a Pointer
1. Declare a Variable:
o Define a regular variable of a specific data type (e.g., int, float, char).
2. Declare a Pointer:
o Define a pointer variable that can hold the memory address of the type of data
you are working with.
3. Assign the Address:
o Use the address-of operator (&) to get the memory address of the variable and
assign it to the pointer.
Example:
#include <stdio.h>
int main() {
int num = 42; // Step 1: Declare a variable
int *ptr = # // Step 2: Declare and initialize the pointer with the address
// Print the value and address
printf("Value of num: %d\n", num); // Prints 42
printf("Address of num: %p\n", &num); // Prints the memory address
printf("Pointer ptr holds: %p\n", ptr); // Prints the memory address stored
printf("Value at ptr: %d\n", *ptr); // Dereferences 'ptr' to print the value
return 0;
}
Dr. Ruma Sinha
Output:
Value of num: 42
Address of num: 0x7ffee3b2acfc // Example memory address
Pointer ptr holds: 0x7ffee3b2acfc
Value at ptr: 42
Write a c program to add two numbers using pointers
Program:
#include <stdio.h>
int main() {
int num1, num2, sum;
int *ptr1, *ptr2; // Declare pointers
// Input two numbers
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Assign the addresses of num1 and num2 to pointers
ptr1 = &num1;
ptr2 = &num2;
// Add the values pointed to by ptr1 and ptr2
sum = *ptr1 + *ptr2;
// Display the result
printf("The sum of %d and %d is: %d\n", *ptr1, *ptr2, sum);
return 0;
}
Output:
Enter the first number: 10
Enter the second number: 20
The sum of 10 and 20 is: 30
Write a C program to illustrate the use of pointers in arithmetic operations.
Program:
#include <stdio.h>
int main() {
int a = 10, b = 5;
int *ptr1 = &a, *ptr2 = &b; // Initialize pointers
// Arithmetic operations using pointers
Dr. Ruma Sinha
int sum = *ptr1 + *ptr2; // Addition
int difference = *ptr1 - *ptr2; // Subtraction
int product = (*ptr1) * (*ptr2); // Multiplication
int quotient = *ptr1 / *ptr2; // Division
// Print results
printf("Values: a = %d, b = %d\n", *ptr1, *ptr2);
printf("Sum: %d + %d = %d\n", *ptr1, *ptr2, sum);
printf("Difference: %d - %d = %d\n", *ptr1, *ptr2, difference);
printf("Product: %d * %d = %d\n", *ptr1, *ptr2, product);
printf("Quotient: %d / %d = %d\n", *ptr1, *ptr2, quotient);
return 0;
}
Output:
Values: a = 10, b = 5
Sum: 10 + 5 = 15
Difference: 10 - 5 = 5
Product: 10 * 5 = 50
Quotient: 10 / 5 = 2
Write a function to swap the values of two variables without using a temporary variable, using
pointers.
Program:
#include <stdio.h>
// Function to swap values using pointers
void swap(int *x, int *y) {
*x = *x + *y; // Step 1: Add the values and store the result in x
*y = *x - *y; // Step 2: Subtract y from the new value of x to get the original
value of x
*x = *x - *y; // Step 3: Subtract the new value of y from x to get original y
}
int main() {
int a, b;
// Input two numbers
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
// Display values before swap
printf("\nBefore swap:\n");
printf("a = %d, b = %d\n", a, b);
Dr. Ruma Sinha
// Swap the values
swap(&a, &b);
// Display values after swap
printf("\nAfter swap:\n");
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
Enter first number: 10
Enter second number: 20
Before swap:
a = 10, b = 20
After swap:
a = 20, b = 10
Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of N real numbers.
Program:
#include <stdio.h>
#include <math.h>
// Function to compute sum, mean, and standard deviation
void computeStats(float *arr, int n, float *sum, float *mean, float *std_dev) {
float temp_sum = 0.0, variance = 0.0;
float *ptr = arr; // Pointer to traverse the array
// Calculate the sum
for (int i = 0; i < n; i++) {
temp_sum += *ptr;
ptr++;
}
*sum = temp_sum;
// Calculate the mean
*mean = temp_sum / n;
// Calculate the variance
ptr = arr; // Reset pointer to the start of the array
for (int i = 0; i < n; i++) {
variance += pow((*ptr - *mean), 2);
ptr++;
}
variance /= n;
// Calculate the standard deviation
Dr. Ruma Sinha
*std_dev = sqrt(variance);
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
float arr[n];
printf("Enter %d real numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%f", &arr[i]);
}
float sum, mean, std_dev;
// Call the function
computeStats(arr, n, &sum, &mean, &std_dev);
// Print the results
printf("Sum: %.2f\n", sum);
printf("Mean: %.2f\n", mean);
printf("Standard Deviation: %.2f\n", std_dev);
return 0;
}
Output:
Enter the number of elements: 5
Enter 5 real numbers:
24759
Sum: 27.00
Mean: 5.40
Standard Deviation: 2.42
Dr. Ruma Sinha
Structure in C
A structure in C is a user-defined data type that allows you to group different types of
variables under a single name. These variables, known as members or fields, can have
different data types (e.g., int, float, char). Structures help organize complex data in a
meaningful way.
Syntax of Structure Declaration
struct structure_name {
data_type member1;
data_type member2;
// Additional members
};
• struct: This keyword is used to define a structure.
• structure_name: The name of the structure, which is used to refer to the structure type.
• data_type: The type of the member (could be any valid data type such as int, float, etc.).
• member1, member2: The names of the members of the structure.
Example of Structure Declaration
#include <stdio.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
// Declare a structure variable of type 'Student'
struct Student student1;
// Assign values to the members of the structure
printf("Enter name: ");
scanf("%s", [Link]);
printf("Enter age: ");
scanf("%d", &[Link]);
printf("Enter marks: ");
scanf("%f", &[Link]);
// Display the values of the structure members
printf("\nStudent Information:\n");
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
printf("Marks: %.2f\n", [Link]);
return 0;
}
Dr. Ruma Sinha
Output:
Enter name: Rajnikanth
Enter age: 40
Enter marks: 100
Student Information:
Name: Rajnikanth
Age: 40
Marks: 100.00
Differentiate between Array and structures.
Different ways of declaring structure variable.
1. Declaring Structure Variables Separately
#include <stdio.h>
// Structure declaration
struct Student {
char name[50];
int age;
float marks;
};
// Declaring structure variables
struct Student student1, student2;
int main() {
// Assign values to structure members
[Link] = 20;
[Link] = 22;
printf("Student 1 Age: %d\n", [Link]);
Dr. Ruma Sinha
printf("Student 2 Age: %d\n", [Link]);
return 0;
}
2. Declaring and Defining Structure Variable Simultaneously
#include <stdio.h>
// Structure declaration and definition together
struct Student {
char name[50];
int age;
float marks;
} student1, student2; // Declaring variables while defining the structure
int main() {
// Assign values to structure members
[Link] = 20;
[Link] = 22;
printf("Student 1 Age: %d\n", [Link]);
printf("Student 2 Age: %d\n", [Link]);
return 0;
}
3. Declaring and Initializing Structure Variables at the same time
#include <stdio.h>
// Structure declaration
struct Student {
char name[50];
int age;
float marks;
};
int main() {
// Declaring and initializing structure variables
struct Student student1 = {"John", 20, 85.5};
struct Student student2 = {"Alice", 22, 90.0};
// Accessing structure members
printf("Student 1 Name: %s, Age: %d, Marks: %.2f\n", [Link],
[Link], [Link]);
printf("Student 2 Name: %s, Age: %d, Marks: %.2f\n", [Link],
[Link], [Link]);
return 0;
}
Dr. Ruma Sinha
Define a structure named date containing three integer members day, month, and year.
Create two structure variables and initialize them with suitable values and print them in
the format dd/mm/yyyy.
Program:
#include <stdio.h>
// Structure definition
struct Date {
int day;
int month;
int year;
};
int main() {
// Declare and initialize two structure variables
struct Date date1 = {15, 10, 2024}; // 15th October 2024
struct Date date2 = {20, 01, 2025}; // 20th January 2025
// Print the dates in dd/mm/yyyy format
printf("Date 1: %02d/%02d/%04d\n", [Link], [Link], [Link]);
printf("Date 2: %02d/%02d/%04d\n", [Link], [Link], [Link]);
return 0;
}
Output:
Date 1: 15/10/2024
Date 2: 19/01/2025
Define a structure named time containing three integer members hour,
minute, and second. Create two structure variables, input the values and
print them in the format hh:mm:ss.
Program:
#include <stdio.h>
// Structure definition
struct Time {
int hour;
int minute;
int second;
};
int main() {
// Declare two structure variables
struct Time time1, time2;
Dr. Ruma Sinha
// Input values for the first time
printf("Enter hour, minute, and second for time1 (hh mm ss): ");
scanf("%d %d %d", &[Link], &[Link], &[Link]);
// Input values for the second time
printf("Enter hour, minute, and second for time2 (hh mm ss): ");
scanf("%d %d %d", &[Link], &[Link], &[Link]);
// Print the times in hh:mm:ss format
printf("Time 1: %02d:%02d:%02d\n", [Link], [Link], [Link]);
printf("Time 2: %02d:%02d:%02d\n", [Link], [Link], [Link]);
return 0;
}
Output:
Enter hour, minute, and second for time1 (hh mm ss): 10 30 20
Enter hour, minute, and second for time2 (hh mm ss): 11 40 31
Time 1: 10:30:20
Time 2: 11:40:31
Dr. Ruma Sinha