logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jun15/charExists.c

/*

	writing a function that takes both a string and an character
	and determines if the specified character exists.

	this is also an example of how to write a function that takes a whole array as an argument

*/


#include <stdio.h>

int charExists(char s[], char c);//function declaration

/*
	if you're going to write a function that takes an array, you need to indicate that one
	of the arguments is an array. above is one such way you do it.

*/


int main(){

	char str[128];
	char ch;


	printf("Enter a string: ");
	fgets(str, 128, stdin);

	printf("Enter a character: ");
	ch = getchar(); //getchar is a function that gets a single character from stdin (the user)


	if(charExists(str, ch) == 1)
		printf("The character %c exists in the string\n", ch);
	else
		printf("The character %c does not exist in the string\n", ch);


	return 0;
}


int charExists(char s[], char c){

 //iterate through the string until we find character c
	for(int i = 0; s[i] != '\0'; i++){
		if(s[i] == c) //we found the character
			return 1;
	}
	//if we end up here, the charater was not found
	return 0;

}