Skip to lab content

UNIT 04 · Strings

Find the position of a character

EXERCISE 04CC173 sample runs

THE SYLLABUS QUESTION

What you need to solve

Write a C program that displays the position of a character ch in the string S or -1 if S does not contain ch.
Input format & conventions

Line 1: string S (at most 255 bytes). Line 2: exactly one character, including a space if required. Output is the first 1-based position, or -1. Examples use ASCII text.

UNDERSTAND THE IDEA

Explanation

Scan the string from left to right. The first matching byte determines the result.

C indexes start at 0, but this solution reports a position starting at 1. If no match is found, the initial value -1 is retained.

PLAN BEFORE CODING

Algorithm

  1. Read the main string and one-character search line.
  2. Initialize position to -1.
  3. Compare each byte with the search character.
  4. On the first match, save i + 1 and stop.
  5. Display the position.

SEE THE CONTROL FLOW

Flowchart

Follow the arrows from Start. Diamonds ask a question; labeled arrows show the answer. A returning arrow repeats a loop. Function internals are grouped where needed; later input checks follow the rules in the program.

Flowchart for Find the position of a character: input, decisions, processing, output and loop paths

On a phone, scroll sideways to read the diagram at full size. Open full-size flowchart ↗

C17

Complete C program

Download .c
#include <stdio.h>
#include <string.h>

int readLine(char text[], size_t capacity) {
    if (fgets(text, (int)capacity, stdin) == NULL) return 0;
    size_t length = strlen(text);
    if (length > 0 && text[length - 1] == '\n') text[--length] = '\0';
    else if (!feof(stdin)) {
        int ch = getchar();
        if (ch != '\n' && ch != EOF) return 0;
    }
    if (length > 0 && text[length - 1] == '\r') text[length - 1] = '\0';
    return 1;
}

int main(void) {
    char text[256], character[8];
    int position = -1;
    if (!readLine(text, sizeof text) || !readLine(character, sizeof character) ||
        strlen(character) != 1) {
        puts("Invalid input."); return 1;
    }
    for (int i = 0; text[i] != '\0'; ++i) {
        if (text[i] == character[0]) { position = i + 1; break; }
    }
    printf("Position: %d\n", position);
    return 0;
}
Open in compiler ↗

Code loads into the existing compiler. Enter the sample input there; sign-in and execution rules stay the same.

Compile and run locally
gcc -std=c17 character-position.c -o lab
./lab

On Windows, run .\lab.exe after compiling with GCC. The interest program requires the math library where applicable.

FOLLOW THE VALUES

Dry run

Step / stateOperationResult
String = banana; character = nIndex 0: bNo match
Index 1: aNo matchContinue
Index 2: nMatchPosition = 3

CHECK THE BEHAVIOR

Sample input & output

Each output below was produced by compiling and running this exact program. Input values are entered in the stated order; the examples do not print input prompts.

Sample 1

INPUT
banana
n
OUTPUT
Position: 3

Sample 2

INPUT
hello
z
OUTPUT
Position: -1

Sample 3

INPUT
hello world
 
OUTPUT
Position: 6

Common mistakes

  • Explain whether your result is a position or a zero-based index.
  • Stop at the first match if the string contains the character more than once.

WHY THIS GROWTH RATE?

Time and space complexity

Time O(L); O(L) input storage and O(1) additional working space.

Let L be the string length. In the worst case, the character is absent or appears at the end, so the scan compares all L characters. The first match stops the scan.

The search itself ranges from O(1) for a first-character match to O(L) in the worst case. Reading and validating the whole string already takes O(L), so the complete program is O(L). The string uses O(L) input storage; the search index and result use O(1) extra space.

Big-O describes how work grows as the stated input quantity grows; fixed factors and lower-order terms are omitted. The analysis treats fixed-width arithmetic as constant cost and the published limits as practical safety bounds.