💻
B.TECH I YEAR • I SEMESTER • R25

Programming for Problem Solving - Lab Manual

C Programming Laboratory • Program Solution

📘 R25 Regulation 🎓 I Year 📚 I Semester 💻 C Programming 🧪 Lab Program
Selected Program

Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t contain ch.

← All Lab Programs

Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t contain ch.

C Program
//position of a character ch in the string S or – 1 if S doesn‘t contain ch.
#include <stdio.h>
#include <string.h>

int main() {
    char str[100], ch;
    char *position;

    // Input string and character
    printf("Enter the string: ");
    fgets(str, sizeof(str), stdin);

    printf("Enter the character to find: ");
    scanf("%c", &ch);

    // Use strchr to find the first occurrence of ch in string S
    position = strchr(str, ch);
    
    // Check if character is found
    if (position) {
        // Output the index of the character
        printf("Position of '%c' in string: %d\n", ch, position - str);
    } else {
        printf("-1\n");  // If the character is not found
    }

    return 0;
}

OUTPUT
Enter the string: studyglance
Enter the character to find: g
Position of 'g' in string: 5

💻 Run This C Program

Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t contain ch.
The selected C program is loaded automatically. Edit the code, provide input through STDIN and click Run.

The compiler is embedded using OneCompiler. Your program runs in the embedded C environment; Study Glance does not execute C code directly on your web server.
← Back to PPS Lab Programs 📚 All Lab Manuals