Programming for Problem Solving

GTU Practical 37

37. Write a program to find a character from a given string.
#include<stdio.h>  ( this applies in the given code )

#include

int main() {
char str[100], ch;
int found = 0;

// Input the string
printf(“Enter a string: “);
fgets(str, sizeof(str), stdin);

// Input the character to find
printf(“Enter the character to find: “);
scanf(“%c”, &ch);

// Traverse through the string and find the character
for(int i = 0; str[i] != ‘\0’; i++) {
if(str[i] == ch) {
printf(“Character ‘%c’ found at position %d\n”, ch, i + 1);
found = 1;
break;
}
}

if (!found) {
printf(“Character ‘%c’ not found in the string.\n”, ch);
}

return 0;
}

OUTPUT

Enter a string: AD
Enter the character to find: D
Character ‘D’ found at position 2

GTU STUDY