Structured Programming Quiz 4V1
Student Name /ID:
Q1: What is the output of the following code:
#include <stdio.h>
int main() {
char string[] = "C programming is cool!";
int y = 0;
char a = 'o';
char b = '*';
printf(" %s\n", string);
for (int i = 0; string[i] != '\0'; i++) {
if (string[i] == a) {
y++;
string[i] = b;
}
}
printf(" %s\n", string);
printf("a:%c y: %d\n", a, y);
return 0;
}
Q2: Write a C function named count_char that takes two parameters:
1. A character array (string).
2. A character to count within the string.
The function should return the number of times the specified character appears in the string.
Do not use any built-in string functions.
Implement the function separately and call it from main.
In main, prompt the user to enter a string and a character, then call the function and
display the result.
#include <stdio.h>
// Function to count occurrences of a character in a string
int count_char(char str[], char ch) {
int count = 0;
int i = 0;
while (str[i] != '\0') {
if (str[i] == ch) {
count++;
i++;
return count;
}
int main() {
char str[100];
char ch;
// Prompt user for a string (reads until space or newline)
printf("Enter a string (no spaces): ");
scanf("%s", str);
// Prompt user for a character
printf("Enter a character to count: ");
scanf(" %c", &ch); // Space before %c skips leftover newline
// Call the function and display the result
int result = count_char(str, ch);
printf("The character '%c' appears %d time(s) in the string.\n", ch, result);
return 0;