
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
What is an anagram in C language?
Anagram strings are nothing but, all the characters that occur for the same number of times in another string, which we call as anagrams.
A user enters two strings. We need to count how many times each letter ('a' to 'z') appears in them and then, compare their corresponding counts. The frequency of an alphabet in a string is how many times it appears in it.
If two strings have same count of the frequency of particular alphabet then, we can say those two strings are anagrams.
Example 1
String 1 − abcd
String 2 − bdac
These two strings have same letters which appear once. So, these two strings are anagrams.
Example 2
String 1 − programming
String 2 − gramming
Output − The strings are not anagrams.
Example
Following is the C program for an anagram −
#include <stdio.h> int check_anagram(char [], char []); int main(){ char a[1000], b[1000]; printf("Enter two strings
"); gets(a); gets(b); if (check_anagram(a, b)) printf("The strings are anagrams.
"); else printf("The strings aren't anagrams.
"); return 0; } int check_anagram(char a[], char b[]){ int first[26] = {0}, second[26] = {0}, c=0; // Calculating frequency of characters of the first string while (a[c] != '\0') { first[a[c]-'a']++; c++; } c = 0; while (b[c] != '\0') { second[b[c]-'a']++; c++; } // Comparing the frequency of characters for (c = 0; c < 26; c++) if (first[c] != second[c]) return 0; return 1; }
Output
When the above program is executed, it produces the following output −
Run 1: Enter two strings abcdef deabcf The strings are anagrams. Run 2: Enter two strings tutorials Point The strings aren't anagrams.
- Related Articles
- What is an identifier in C language?
- What is an inline function in C language?
- What is an array of structures in C language?
- What is an algorithm and flowchart in C language?
- What is an auto storage class in C language?
- What is an extern storage class in C language?
- What is an identifier and its rules in C language?
- What is out of bounds index in an array - C language?
- What is malloc in C language?
- What is Calloc in C language?
- What is Realloc in C language?
- What is C++ programming language?
- What is void pointer in C language?
- What is strlen function in C language?
- What is strcoll() Function in C language?
