Home » C solved programs

C program to compare two characters

In this code snippet/program/example we will learn how to compare two characters in c programming language?

Here we will implement this program “c program to compare two characters” using two methods. First will be simple method in which we will take two characters and compare them, and second we will create a user define function that will take two arguments and returns 0 or -1.

This program will read two character values from the user and compare them, if the characters are equal program will print “Characters are equal” and if characters are not equal, program will print “Characters are not equal”.

We will also compare characters using user define function, function name will be compareCharacters(). This function will take two characters as arguments. If characters are equal function will return 0 otherwise function will return -1.

C Code Snippet/ Program - Compare Two Characters in C programming language

/*C - Program to compare two characters.*/
#include<stdio.h>
int main(){
	char c1,c2;
	
	printf("Enter two characters: ");
	scanf("%c %c",&c1,&c2); //space b/w %c and %c
	
	if(c1==c2)
		printf("Characters are equal.\n");
	else
		printf("Characters are not equal.\n");
	
	return 0;
}

Using user define function

#include<stdio.h>

char compareCharacters(char a,char b){
	if(a==b)
		return 0;
	else
		return -1;
}

int main(){
	char c1,c2;
	
	printf("Enter two characters: ");
	scanf("%c %c",&c1,&c2); //space b/w %c and %c
	
	if(compareCharacters(c1,c2)==0)
		printf("Characters are equal.\n");
	else
		printf("Characters are not equal.\n");
	
	return 0;
}

Output


    First run:
    Enter two characters: x x 
    Characters are equal. 

    Second run:
    Enter two characters: x y 
    Characters are not equal.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.