Lab 6: Strings in C

Lab Report Information
Lab No.: 6
Title: Strings in C
Course: Computer Programming (CT 101), I Year I Part
Credit: Important Notes
C Programming Lab Report: Theory for Lab 6
Strings in C
This C Programming Lab Report explores the fundamentals of handling Strings in C. A string is not a basic data type but is implemented as an array of characters, terminated by a special null character (`\0`).
Declaration and Initialization
A string is declared as a character array: char string_variable[size];
. It can be initialized in two ways:
char str[] = "Nepal";
(The null character is added automatically).char str[] = {'N', 'e', 'p', 'a', 'l', '\0'};
(The null character must be added manually).
String Handling Functions (from ``)
C provides a rich library for string manipulation:
strcpy()
: Copies a string.strcat()
: Concatenates (joins) two strings.strlen()
: Returns the length of a string.strcmp()
: Compares two strings (case-sensitive).
C Programming Lab Report: Programs for Lab 6
1. Concatenate Two Strings Without Library Function
Question:
Write a program in C to concatenate two strings entered by the user without using a library function.
Program Code:
#include <stdio.h> #include <conio.h> void main() { char str1[50], str2[50]; int i = 0, j = 0; clrscr(); printf("\nEnter first string: "); gets(str1); printf("Enter second string: "); gets(str2); // Find the end of the first string while (str1[i] != '\0') { i++; } // Append the second string to the first while (str2[j] != '\0') { str1[i] = str2[j]; i++; j++; } str1[i] = '\0'; // Add null terminator printf("\nConcatenated string: %s", str1); getch(); }
Output:
Enter second string: bhandari
Concatenated string: diwakarbhandari
Algorithm:
- Start
- Declare two character arrays, `str1` and `str2`.
- Read two strings from the user.
- Find the length of `str1` by looping until its null terminator is found.
- Append each character of `str2` to the end of `str1`.
- Place a null terminator at the end of the newly formed `str1`.
- Print the concatenated string `str1`.
- Stop.
Flowchart:
Flowchart shows reading two strings, finding the end of the first string with a loop, appending the second string with another loop, and then printing the result.
2. Palindrome Check Without Library Function
Question:
Write a program in C to check if a string is a palindrome without using library functions.
Program Code:
#include <stdio.h> #include <conio.h> void main() { char str[100]; int i = 0, len = 0, flag = 1; clrscr(); printf("\nEnter a string: "); gets(str); // Calculate length while (str[len] != '\0') { len++; } // Check for palindrome while (i < len / 2) { if (str[i] != str[len - 1 - i]) { flag = 0; break; } i++; } if (flag == 1) { printf("\nThe string is a palindrome."); } else { printf("\nThe string is not a palindrome."); } getch(); }
Output:
The string is a palindrome.
Algorithm:
- Start
- Read a string.
- Calculate its length.
- Compare the first character with the last, the second with the second-to-last, and so on, until the middle is reached.
- If all corresponding characters match, it is a palindrome.
- Otherwise, it is not a palindrome.
- Print the result.
- Stop.
Flowchart:
Flowchart shows reading a string, calculating its length, then entering a loop that compares characters from both ends moving inwards. A flag is used to track if a mismatch is found.
3. Compare Two Strings Without Library Function
Question:
Write a program to compare two strings entered by the user without using a library function.
Program Code:
#include <stdio.h> #include <conio.h> void main() { char str1[100], str2[100]; int i = 0, flag = 1; clrscr(); printf("\nEnter first string: "); gets(str1); printf("Enter second string: "); gets(str2); while (str1[i] != '\0' || str2[i] != '\0') { if (str1[i] != str2[i]) { flag = 0; break; } i++; } if (flag == 1) { printf("\nStrings are equal."); } else { printf("\nStrings are not equal."); } getch(); }
Output:
Enter second string: diwakar
Strings are equal.
Algorithm:
- Start
- Read two strings, `str1` and `str2`.
- Iterate through both strings simultaneously, character by character.
- If a mismatch is found at any position, set a flag and break the loop.
- After the loop, check the lengths to ensure one is not a substring of the other.
- If no mismatch was found and lengths are equal, the strings are equal. Otherwise, they are not.
- Print the result.
- Stop.
Flowchart:
Flowchart shows reading two strings and then entering a loop that compares characters at the same index. If a mismatch is found, a flag is set, and the loop terminates.
4. Count Characters and Words
Question:
Write a program to calculate the total number of characters and words in a given sentence.
Program Code:
#include <stdio.h> #include <conio.h> void main() { char str[100]; int i, charCount = 0, wordCount = 1; clrscr(); printf("\nEnter a string: "); gets(str); for (i = 0; str[i] != '\0'; i++) { charCount++; if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') { wordCount++; } } printf("\nTotal characters: %d", charCount); printf("\nTotal words: %d", wordCount); getch(); }
Output:
Total characters: 23
Total words: 5
Algorithm:
- Start
- Read a sentence.
- Initialize `charCount` to 0 and `wordCount` to 1.
- Iterate through the string.
- Increment `charCount` for every character.
- Increment `wordCount` every time a space is encountered.
- Print `charCount` and `wordCount`.
- Stop.
Flowchart:
Flowchart shows initializing counters, reading a string, and looping through it. Inside the loop, it increments the character count always and the word count only when a space is found.
5. Generate String Patterns
Question:
Write a program to generate the given patterns.
Pattern i:
#include <stdio.h> int main() { char str[] = "NEPAL"; int i, j; for (i = 0; i < 5; i++) { for (j = 0; j <= i; j++) { if (i % 2 != 0) { printf("%c", str[i] + 32); // Lowercase } else { printf("%c", str[i]); // Uppercase } } printf("\n"); } return 0; }
Output:
N ee PPP aaaa LLLLL
Pattern ii:
#include <stdio.h> #include <string.h> int main() { char str[] = "pulchowk"; int len = strlen(str); int i, j, k; for (i = 0; i < len; i++) { for (j = 0; j < len - 1 - i; j++) { printf(" "); } k = len - 1 - i; for (j = 0; j <= i; j++) { printf("%c", str[k++]); } printf("\n"); } return 0; }
Output:
p ul lch chow howk owk wk k
Algorithm (for Pattern i):
- Start
- Use an outer loop `i` from 0 to 4.
- Use an inner loop `j` from 0 to `i`.
- Inside the inner loop, check if `i` is odd. If so, print the `i`-th character of "NEPAL" in lowercase. Otherwise, print it in uppercase.
- After the inner loop, print a newline.
- Stop.
Discussion and Conclusion
In this C Programming Lab Report for Lab 6: Strings in C, we tackled fundamental programming tasks focusing on string manipulation, palindrome checking, and string comparison. From this, we learned how to manipulate strings manually without relying on library functions, how to form patterns from strings, and how to solve common problems related to strings. An error was noted in one of the pattern-generating programs, which was solved by revising the loop logic, highlighting the importance of careful algorithm design.