- Asked 2/16
- 2071 Chaitra · 4 marks
- 2068 Chaitra · 8 marks
Reverse a string using functions
Short answer
countChars returns the string length by counting characters until '\0'. reverse copies characters from the end of the source to the start of the destination and appends '\0'. main reads with fgets, strips the newline, and prints length and reversed string. For 'Pulchowk Campus', length=15, reverse='supmaC kwohcluP'.
Write a C program to read a string and display its reverse. Use user defined function to count number of characters in it and to reverse it.
Method.
- Read the string (using
fgetsso that spaces are accepted). countChars()returns the number of characters by counting until the null character'\0'.reverse()copies the characters from the last to the first into a second array and puts'\0'at the end.main()displays the length and the reversed string.
#include <stdio.h>
int countChars(char s[])
{
int n = 0;
while (s[n] != '\0')
n++;
return n;
}
void reverse(char s[], char r[])
{
int n = countChars(s);
for (int i = 0; i < n; i++)
r[i] = s[n - 1 - i];
r[n] = '\0';
}
int main(void)
{
char str[100], rev[100];
printf("Enter a string: ");
fgets(str, sizeof str, stdin);
for (int i = 0; str[i]; i++) /* remove trailing newline */
if (str[i] == '\n') str[i] = '\0';
reverse(str, rev);
printf("Length = %d\nReverse = %s\n", countChars(str), rev);
return 0;
}
Sample run
Input: Pulchowk Campus
Enter a string: Length = 15
Reverse = supmaC kwohcluP
The length of "Pulchowk Campus" is 15 (the space is counted).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Significance of user defined functions · Computer Programming, chapter 6
- Switch versus user defined function · Computer Programming, chapter 5
- Rewrite string characters alphabetically · Computer Programming, chapter 7
- Display characters between given ranges · Computer Programming, chapter 5
- Palindrome string using function · Computer Programming, chapter 7
- Reverse array and display via pointer · Computer Programming, chapter 9
- 8086 ALP: count vowels and display string · Microprocessor, chapter 3
- 8086 ALP: display only alphabetic characters · Microprocessor, chapter 3
- Display N characters using default arguments · Object Oriented Programming, chapter 3
- 8086 ALP: count vowels, consonants, numerals · Microprocessor, chapter 3