//Program to find max occurring character in string
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100 // Maximum string size, change to make string smaller or larger
#define MAX_CHARS 255 // Maximum characters allowed for characters
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do{
clrscr();
i=0;
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
i=0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
i++;
}
// Finds maximum frequency of character
max = 0;
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] > freq[max])
max = i; //to print no. of times
}
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
}while(ch=='Y'||ch=='y');
}
When I give it the input: "aaaaeeee", the output is "a" occurring 4 times, but "e" occurs 4 times too. I know this is sorted by ascii values and thats why it gives "a" as output, but what can I do in this program that the output gives both "a" and "e" as output when a case like this occurs?
Add max calculation ahead
i = 0;
max = 0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1;
if (freq[ascii] > max) max = freq[ascii]; // <==== here
i++;
}
Note that this is the max number of the same character you might have.
Then display all chars which maximum is equal to max
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
To fix the endless loop, before the while add char c ; while ((c = getchar()) != EOF && c != '\n');
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n'); // <== note the ';'
} while(ch=='Y'||ch=='y');
Note that you shouldn't use gets, reason is explained here.
Whole code:
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do {
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
for(i=0,max=0 ; str[i] != '\0' ; i++)
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
if (freq[ascii] > max) max = freq[ascii];
}
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n');
}while(ch=='Y'||ch=='y');
}
Above this line
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
Delete it and add this code
for(i=0;i<MAX_CHARS;i++)
{
if(freq[i]==freq[max])
{
printf("\nMaximum occurring character is '%c' = %d times.", i, freq[i]);
}
}
Related
My first program. I would like it if the user enters a word made of letters and then it uses my loop function to output mixed up even and odd characters. Currently I cannot get it to compile. Bonus points if someone can show me how to loop the users input so after it asks the size to make the array, it prompts the user that many times for an "element" or word so that the function can scramble it and output it.
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
char str[size];
printf("How many elements?");
scanf("%d", &size);
printf("Please type an element: ");
//Get input from user
str[0] = scanf("%s", str);
transform(str);
printf("Please type another element: ");
//Get another input from user
str[1] = scanf("%s", str);
transform(str);
//This is the loop function that I programmed
char transform(char str[]);
{
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 == 0)
{
printf("%c", str[i]);
}
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 != 0)
{
printf("%c", str[i]);
}
}
printf("\n");
return 0;
}
}
#include <stdlib.h>
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
printf("How many elements?");
scanf("%d", &size);
for (int i = 0; i < size; ++i)
{
printf("Please type an element: ");
char str[2048]; //declare a wide buffer to be able to store lots of chars
scanf("%s", str);
transform(str);
}
return 0;
} //end your main here, by putting closing brace
char transform(char str[]) //define transform without semicolon, and outside of main
{ //This is the loop function that I programmed
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 == 0)
printf("%c", str[i]);
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 != 0)
printf("%c", str[i]);
}
printf("\n");
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am studying the c language in our class I create some code to find a some number inside other array but when I try it with char value my code is not working in same as working with int value.
This is my code:
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
//printf("%d\t", (i+1));
//if ( i + 1 == num ) {
// scanf("%c", &a[i]);
//} else {
scanf("%c", &a[i]);
//}
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf("%c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
I try to fixed many time but each time I get error, so the above one is working but it scape the some input value during input.
Thank you WhozCraig, user3121023 for your advices, the whitespace in scanf(" %c", &a[i]); and scanf(" %c", &ele); make some unwanted inputs so this is a my code and its working like charm. :))
I just add space before the %c and every thing is okay.
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
printf("%d\t", (i+1));
scanf(" %c", &a[i]);
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf(" %c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
There is a problem in your program that causes surprising behavior:
scanf("%d", &num) reads a number from standard input but leaves the newline typed by the user pending as the next character to be read.
Further calls to scanf("%c", &a[i]); read this pending newline and num-1 more characters from the user, leaving the rest of his input pending...
The final scanf("%c", &ele); reads whatever byte is pending in stdin, either a character from the user or the pending newline.
Hence the program behaves as if it does not execute the last scanf().
You should read input from the user one line at a time with fgets() or flush the pending newline with a loop:
#include <stdio.h>
int main() {
int num, i, c;
char a[99], ele;
printf("Enter the number of character:");
// get the length of array by the num value
if (scanf("%d", &num) != 1 || num < 0 || num > 99)
return 1;
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
printf("Enter the characters on a single line: \n");
// a loop for getting values for our a[array]
for (i = 0; i < num; i++) {
if (scanf("%c", &a[i]) != 1)
return 1;
}
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
printf("Enter the character to be searched: ");
// get the value for ele, to use ele for searching inside our a[array]
if (scanf("%c", &ele) != 1)
return 1;
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
// use a for loop
for (i = 0; i < num && ele != a[i]; i++) {
i++;
}
if (i < num) {
printf("Character %c found at the offset %d\n\n\n", ele, i);
} else {
printf("Character %c Not Found!\n\n\n", ele);
}
return 0;
}
I want to do a program that ask to the user to give one character, then enter... until he wants to stop by pressing enter and no caracters.
Then, the program will say: "you gave the caracters ...."
for example:
give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')
result: You gave the caracters: kl
My code doesnet work because when i just press enter, nothing happen. Here is the code:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}
printf("The string is: ");
while (j < i) {
printf("%s", str[j]);
j += 1;
}
return 0;
}
You can do it with c = getchar(); or c = fgetc(stdin) function:
#include <stdio.h>
#define N 1000
int
main ()
{
int i = 0;
int j = 0;
int c;
char str[N];
while (1)
{
c = fgetc(stdin); // or c = getchar();
if ( (c != EOF) && (c != 0x0A ) ) // 0x0A = 'nl' character
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
This is my string!
element number str[1]=T
element number str[2]=h
element number str[3]=i
element number str[4]=s
element number str[5]=
element number str[6]=i
element number str[7]=s
element number str[8]=
element number str[9]=m
element number str[10]=y
element number str[11]=
element number str[12]=s
element number str[13]=t
element number str[14]=r
element number str[15]=i
element number str[16]=n
element number str[17]=g
element number str[18]=!
The string is: This is my string!
Or you can use your original scanf("%s", &str1);
#include <stdio.h>
#define N 1000
int main ()
{
int i = 0;
int k = 0;
int c;
int len;
char str[N];
char str1[N];
scanf("%s", &str1);
len = strlen(str1);
for(k = 0; k < len; k++)
{
c = str1[k];
if ( (c != EOF) && c != '\n') // EOF will work for ^D on UNIX
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
12345
element number str[1]=1
element number str[2]=2
element number str[3]=3
element number str[4]=4
element number str[5]=5
The string is: 12345
As stated in this answer scanf will not return until you give it a string, i.e. it skips whitespace.
As suggested in the answer and in general, using fgets is the better option.
Edit: A way to accomplish what you want would look like this:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
do {
printf("element number str[%d] : ", i);
fgets(&str[i], 3, stdin);
i++;
} while (str[i - 1] != '\n');
printf("The string is: ");
while (i > j) {
printf("%c", str[j]);
j++;
}
return 0;
}
In the fgets you use the number 3 because pressing enter gives both a newline character [/n] and a return carriage [/r].
I am new to C programming so please do forgive my naivety. The following program when outputted fails to print the last character of the input string as the first character of the output string.
For example:
Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh
Why is the o not printing?
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf("%d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf("%c", &string[i]);
}
printf("The reversed string is: ");
for (int i = (n - 1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
There is a side effect you take care of:
After scanf("%d", &n);, there is a pending newline in the input stream buffer.
When you later input n characters, scanf("%c", &string[i]) first reads the pending newline, then the n-1 first characters you type and the remainder of your input stays in the input buffer.
scanf() is a very clunky function. It is difficult to use properly.
Here is a way to fix your problem:
#include <stdio.h>
int main() {
char string[10000];
int i, n, c;
printf("Enter no. of elements: ");
if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
return 1;
// read and discard pending input
while ((c = getchar()) != '\n' && c != EOF)
continue;
printf("Enter string: ");
for (i = 0; i < n; i++) {
if (scanf("%c", &string[i]) != 1)
break;
}
// the above loop could be replaced with a single call to fread:
// i = fread(string, 1, n, stdin);
printf("The reversed string is: ");
while (i-- > 0) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Your scanf() should start with a space( more info about that ). Here is the code:
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf(" %d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf(" %c", &string[i]);
}
/* Just to be safer. */
string[n] = '\0';
printf("The reversed string is: ");
for (int i = (n-1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Adding the space to the format string enables scanf to consume the
newline character from the input that happens everytime you press
return. Without the space, string[i] will receive the
char '\n'
So, merely one space is put before format specifier %c at line 11.
scanf(" %c", &string[i]);
I am trying to make a program that will use getchar() to read three integers and store it in an array but something is wrong in my code.
#include <stdio.h>
int main( )
{
printf("Please enter three digit number 100 to 999: ");
int numEntered[2];
numEntered = getchar();
for (int i = 0; i<3; i++) {
printf("%d", numEntered[i])
}
}
Try this:
#include <stdio.h>
int main(){
printf("Please enter three digit number 100 to 999: ");
int numEntered[3];
for (int i = 0; i<3; i++){
scanf("%d", &numEntered[i]);
printf("%d", numEntered[i]);
}
return 0;
}
you need to read a value inside the for loop! Second thing, by reading with getchar(), you are getting the ascii value of the character, so.. if you read "1" and print with %d, you actually printing 49!
See the ascii table here: http://www.asciitable.com/index/asciifull.gif
let's try and and think about the problem here:
do you want to read and store an integer value? if yes -> use scanf
do you want to read a number digit by digit? if yes -> use getchar
do you want to make sure what you read has exactly 3 digits? if yes...what do you do when it does not?
if reading digit by digit, make sure you are reading numbers; getchar reads characters -> use atoi funtion or check ascii value;
Putting it all together(some assumptions were made):
int main()
{
char digits[3]; // don't use ints to store chars...
printf("enter the 3 digit number - 100 to 999: ");
for (int i=0;i<3;i++) // only the first 3 chars are read
{
char c = getchar();
if (char < '0') || (char > '9')
{
printf("invalid digit!");
exit(0);
}
digits[i] = c;
}
printf("the number entered is: %c%c%c", digits[0],digits[1],digits[2]);
}
You don't use getchar to get integer values.
Use scanf() instead.
Try this:
#include <stdio.h>
int main( )
{
printf("Please enter three digit number 100 to 999: ");
int numEntered[3];
for (int i = 0; i<3; i++){
scanf("%d",&a[i]);
printf("%d", numEntered[i]);
}
}
numEntered = getchar();
(1) It can not be assigned to the array itself.
(2) getchar() reads one character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void){
char digits[4] = {0};//4: 3 character + NUL character
int ch, value;
do {
printf("Please enter three digit number 100 to 999: ");
for(int i = 0; i < 3 && (ch = getchar()) != '\n' && ch != EOF; ++i){
digits[i] = ch;
}
if(ch != '\n')
while((ch = getchar()) != '\n')
if(!isspace(ch))//invalid input
*digits = 0;
value = atoi(digits);
} while(value < 100 || 999 < value);
char *rotate_left(char digits[4]);
printf("%d\n", value);
printf("%d\n", atoi(rotate_left(digits)));
printf("%d\n", atoi(rotate_left(digits)));
return 0;
}
char *rotate_left(char digits[4]){
char temp = digits[0];
digits[0] = digits[1];
digits[1] = digits[2];
digits[2] = temp;
return digits;
}