Searching a char value inside char array in C [closed] - c

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;
}

Related

How can a user enter 10 elements in an array defined for 100 elements?

Here, I want to take input from the user in an array. The condition is the array size should not exceed 100 elements. But, if the user has only 10 elements as input, what can he do? Because he will not be able to stop the loop after 10 elements as I have defined it for 100.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* A;
int i;
A = (int*)malloc(100*(sizeof(A)));
for(i=0; i<100; i++)
{
scanf("%d", &A[i]);
}
return 0;
}
There's a few ways to do this. Here are two potential options:
First, you could add a sentinel value that the user enters to stop input, such as a negative number, zero, or a non-number. Then check the input and break if you encounter your sentinel value.
Secondly, have the user enter the number of values they wish to enter first, and make that the ending condition of your for loop. for(i=0; i != num_entries && i<100; i++)
There needs to be some way for the user to tell the program that he's done inputting values.
You could have the user first enter the number of values he wants to read:
int count;
printf("Number of values: ");
int rval = scanf("%d", &count);
if (rval == 1) {
for(i=0; i<count && i<100; i++) {
rval = scanf("%d", &A[i]);
if (!rval) {
int c;
while ((c=getchar()) != '\n' && (c != EOF));
}
}
}
Or you could have the user enter values continuously until a special value is entered:
printf("Enter values (enter -1 to stop): ");
for(i=0; i<count; i++) {
int value;
int rval = scanf("%d", &value);
if (!rval) {
int c;
while ((c=getchar()) != '\n' && (c != EOF));
} else if (value != -1) {
A[i] = value;
} else {
// -1 was entered
break;
}
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* A;
int i;
A = (int*)malloc(100*(sizeof(*A)));
for(i=0; i<100; i++)
{
int numEl = scanf("%d", &A[i]);
if(numEl!=1) break;
}
free(A);
printf("Read %d values\n", i);
return 0;
}
Just break if you found anything, but a number:
gcc q.c && ./a.out
1
2
3
4
end
Read 4 values
char opp="";
int i=0;
while(opp!="*")
{
printf("Enter element %d :",i+1);
scanf("%d",&A[i]);
// You code here
printf("press * to stop:");
opp=getch();
i++;
if (i>=100)
break;
}
Try this .. Until the user input * it will keep on asking to input

Keep characters in an array

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].

Maximum number of Characters in a character array

//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]);
}
}

Why is this reverse string program not working?

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]);

Checking if all elements in array are zero

I'm having trouble determining if two words entered are anagrams.
#include <stdio.h>
#include <string.h>
int main() {
char ch;
int letter_count[26] = {0};
int i;
int sum = 0;
printf("Enter first word: ");
do
{
scanf("%c", &ch);
letter_count[ch - 'a']++;
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n");
printf("Enter second word: ");
do
{
scanf("%c", &ch);
letter_count[ch - 'a']--;
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
for(i = 0; i < 26; i++)
if(letter_count[ch] != 0)
sum++;
if (sum == 0)
printf("anagrams");
else
printf("not anagrams");
}
I have to use the do while part of the code. I can enter the two words, and it prints out the elements in the array, so that "Mattress" and "Smartest" together would have all the elements be zero. However, I'm having trouble with the last part, which is to use a third loop to check whether all the elements are zero.
I figured I could declare an int before hand and have it increment whenever an element wasn't zero, and I could just have any sum greater than zero not be an anagram. However, it always prints out anagram for me.
In your third loop, using letter_count[ch] will not check the entire array. You should iterate through the array using the loop variable i. That part of the code should be:
for (i=0; i<26; i++)
if (letter_count[i] != 0)
sum++;
To handle both upper case and lower case letters, use topper() or to lower() in <ctype.h> to avoid out-of-bound access.
#include <stdio.h>
#include <string.h>
#include <ctype.h> // <---
int main() {
char ch;
int letter_count[26] = {0};
int i;
_Bool bad = 0;
printf("Enter first word: ");
do
{
scanf("%c", &ch);
if(!isalpha(ch)) // <---
{
puts("Not a letter");
continue;
}
letter_count[tolower(ch) - 'a']++; // <---
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n");
printf("Enter second word: ");
do
{
scanf("%c", &ch);
if(!isalpha(ch)) // <---
{
puts("Not a letter");
continue;
}
letter_count[tolower(ch) - 'a']--; // <---
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n"); // <---
for(i = 0; i < 26; i++)
if(letter_count[i] != 0)
{
bad = 1;
break; // <---
}
if (bad == 0)
printf("anagrams");
else
printf("not anagrams");
}
Take a look at all places marked // <---.

Resources