Function printCharAtOddPos – CTS PATTERN
Print characters at odd positions (1-indexed) in a given string by fixing logical errors in the provided C function.
Understand the Problem
Problem Statement
You are required to correct the syntax of the given code without changing its logic. You can click on Run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.
Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.
The function printCharAtOddPos(char *str) accepts a string str as the input. The function is supposed to print only the characters at the odd positions in the string str.
The function compiles fine but fails to print the desired result due to logical errors.
Your task is to fix the program so that it passes all test cases.
Constraints
- String length can be from 0 to 1000 characters
- String may contain letters, digits, and special characters
- Odd positions are 1-indexed (1st, 3rd, 5th, etc.)
- Memory should be handled properly (no leaks)
- Function should work correctly for empty strings
Examples
HelloHloCharacters at odd positions (1-indexed): Position 1 = 'H', Position 3 = 'l', Position 5 = 'o'. So output is 'Hlo'.
ProgrammingPorgmigCharacters at odd positions: Position 1 = 'P', Position 3 = 'o', Position 5 = 'r', Position 7 = 'g', Position 9 = 'm', Position 11 = 'g'. So output is 'Porgmig'.
AASingle character string has only one character at position 1 (odd position), so output is 'A'.
Empty string has no characters, so no output is produced.
Solution
#include <stdio.h>
#include <string.h>
void printCharAtOddPos(char *str)
{
int index = 0, len = strlen(str);
while (index < len)
{
if (index % 2 == 0)
printf("%c", str[index]);
index += 1;
}
}Step-by-step explanation:
- Calculate string length using
strlen() - Initialize index to 0 to start from the beginning of the string
- Loop through each character while index is less than string length
- Check if current index is even (0, 2, 4...) using
index % 2 == 0 - If condition is true, print the character at that index using
printf() - Increment index to move to next character
Why this works: In 0-indexed arrays, even indices (0, 2, 4...) correspond to odd positions (1, 3, 5...) in 1-indexed counting, which is what the problem requires.