0% found this document useful (0 votes)
24 views1 page

C Programming Lab Task2

Uploaded by

Dinesh Lasantha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views1 page

C Programming Lab Task2

Uploaded by

Dinesh Lasantha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Lab 2

Attempt the following questions and test each of the answers using an appropriate main() function.
Q1 Write a C function to swap two characters. The function prototype is given below.
void cswap(char *a, char *b);

Q2 Study the following code segment and determine the value of i at the end of the code segment.
char d[]="Hello World";
int i;
for(i=0; d[i]; i++); //no body or statement for the loop

Q3 Write a C function to return the length of a string without considering the ending null character.
The function prototype is given below.
int clength(char d[]); //returns length without counting the null

Q4 Write a C function to reverse an input string. The function prototype is given below.
void sreverse(char d[]); // reverses a null terminated string

Hint: Run a loop to scan the array from index 0 to half the length, and swap the characters,
excluding the null character as shown in the below example. Ensure your code works for both
even and odd length strings.
0 1 3 4 5 6 7 8 9 10 11 12
H e l l 0 W o r l d \0

Q5 How Would you implement the above function sreverse() using recursion? Study the code below.
void reverse(char d[], int size){ // size excludes the null
if(size<=1) return; // nothing to do - Base case
cswap(&d[0], &d[size-1]); //swap the first and the last
reverse(&d[1], size-2); //call reverse to swap the rest
}
Why did we call the above function reverse() and not sreverse()? Would the above function
reverse() swap the middle char with itself?
One can now implement sreverse() as,
void sreverse(char d[]) { reverse(d, slength(d)); }

You might also like