counting the number of letter occurences in an Array - c

I want a code that counts the number of occurrences of letters in an array. I have looked at various codes that do the exact, but they all use strings. My issue here is to strictly use arrays.
I have created a code, but it returns: : 0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 : ...
one correct example:
input:
The quick brown fox jumps over the lazy dog.
output:
A: 1
B: 1
C: 1
D: 1
E: 3
F: 1 ...
The following is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int i = 0;
int c;
char counts[26] = {0};
c = getchar();
while (c != EOF && i < 26) {
counts[i] = c;
i += 1;
c = getchar();
}
for (i = 0; i < 26; i++) {
if (counts[i] !=0 )
printf("%c: %d", toupper(c), i);
}
return EXIT_SUCCESS;
}

Using your code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int c;
int counts['Z' - 'A'] = {0};
c = getchar();
while (c != EOF)
{
if (isalpha(c))
counts[(toupper(c)-'A')]++;
c = getchar();
}
for (unsigned int i = 0; i < sizeof(counts)/sizeof(counts[0]); i++)
{
if (counts[i] !=0 )
printf("%c: %d\n", 'A'+i, counts[i]);
}
return EXIT_SUCCESS;
}
Your array is designed to store occurencies of each letter. So the idex of an array must be the latter entered. As you can see I used (toupper(c)-'A') that makes the value of entered char 0 based index.
You must check that entered char is an alphabet char. if (isalpha(c)) do that.
The printout must print characters using the index of array and array content

Related

C beginner question: Array is not printing

I'm trying to produce a simple program which will read a string and print it along with the number of characters in it.
The character count seems fine, but it won't print the full string. For whatever reason, it will print only the second character. I have been reviewing my code and I still cannot figure out why this is happening.
If I input: abcdef
It will print out: 1
b 2
3
4
5
6
Instead of the intended: a 1 b 2 c 3 d 4 e 5 f 6
#include <stdio.h>
int main()
{
char c;
char str[0] = {};
int i;
int charcount;
charcount = 0;
for (i = 0; (c = getchar()) != '#' && c != '\n'; i++) {
c = str[i];
charcount++;
printf("%c %d \n", str[i], charcount);
//if(charcount > 80)
// printf("%d", z[i]);
}
return 0;
}
Any help is appreciated. Thanks.
You have a variable str that is of zero length, and you try to access various elements in it (but it has none, so this is undefined behavior)
Just get rid of it and use c directly:
#include <stdio.h>
int main()
{
char c;
int i;
int charcount;
charcount = 0;
for (i = 0; (c = getchar()) != '#' && c != '\n'; i++) {
charcount++;
printf("%c %d \n", c, charcount);
}
return 0;
}
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
This declaration
char str[0] = {};
is invalid with two respects. The array size shall be greater than zero. And the the braces that initialize the array shall not be empty.
In fact the array is redundant because what you are trying to do is just output entered characters.
This assignment
c = str[i];
does not make sense even if the array was be declared correctly because the entered character is overwritten by the (non-existent) element of the array.
The variable c itself should have the type int.
If you just need to perform this
I'm trying to produce a simple program which will read a string and
print it along with the number of characters in it.
then the program can look for example the following way
#include <stdio.h>
int main(void)
{
size_t i = 0;
for ( int c = getchar(); c != EOF && c != '\n' && c != '#'; c = getchar() )
{
++i;
printf( "%c %zu ", c, i );
}
putchar( '\n' );
return 0;
}
If to enter
abcdef
then the output will be
a 1 b 2 c 3 d 4 e 5 f 6
If you want to use a character array and store entered characters in the array then the program can look like
#include <stdio.h>
int main(void)
{
enum { N = 100 };
char s[N];
int c;
for ( size_t i = 0; i < N && ( c = getchar( ) ) != EOF && c != '\n' && c != '#'; i++ )
{
s[i] = c;
printf( "%c %zu ", s[i], i + 1 );
}
putchar( '\n' );
return 0;
}
The program output will be the same as above if to enter for example abcdef.
I took your question to mean you were looking to store the characters that are entered into an array and print them out as you go. You want to give the array an initial size (I chose 99) and then add characters to the array as you go. You can keep track of the length so you know where the "end" is. There are better ways to manage string data in C, but here you go.
#include <stdio.h>
int main()
{
char c;
char str[99] = {};
int i;
int charcount;
charcount = 0;
for (i = 0; (c = getchar()) != '#' && c != '\n'; i++) {
// c = str[i];
str[i] = c;
charcount++;
printf("%c %d \n", str[i], charcount);
//if(charcount > 80)
// printf("%d", z[i]);
}
return 0;
}
Some additional thoughts:
You probably want to look at something like string.h
If you are going to keep the char array, you need to protect against going over the size of the array
Adding a little blurb about what you expect your program to do, what the requirements are, example input, output, etc would have helped get better answers from the community

Palindrome C program convert capital letters to small letters [duplicate]

This question already has answers here:
Implementation of ToLower function in C
(4 answers)
Closed 5 years ago.
At school Im working on a palindrome C program. I'm almost done, but I would like my program to mark both 'Anna' and 'anna' as a palindrome. I tried some stuff out but nothing really worked.
My code :
#include <stdio.h>
#include <string.h>
int main() {
char palindroom[50],a;
int lengte, i;
int woord = 0;
printf("This program checks if your word is a palindrome.\n");
printf("Enter your word:\t");
scanf("%s", palindroom);
lengte = strlen(palindroom);
for (i = 0; i < lengte; i++) {
if (palindroom[i] != palindroom[lengte - i - 1]) {
woord = 1;
break;
}
}
if (woord) {
printf("Unfortunately, %s is not palindrome\n\n", palindroom);
}
else {
printf("%s is a palindrome!\n\n", palindroom);
}
getchar();
return 0;
}
I've seen some people using tolower from ctype.h but I'd like to avoid that.
So my question is : how do I convert all uppers to lowers in a string?
[ps. some words I may code might seem odd, but that's Dutch. Just erase an o and you'll understand]
Thanks.
the difference between uppercase and lowercase in ASCII table is 32 so you can add 32 if an uppercase letter is in the input to convert it to lowercase ( http://www.asciitable.com/ ) :
if ((currentletter > 64) && (currentletter < 91))
{
char newletter;
newletter = currentletter + 32;
str[i] = newletter;
}
else
{
str[i] = currentletter;
}
modified program :
#include <stdio.h>
#include <string.h>
int main() {
char palindroom[50],a;
int lengte, i;
int woord = 0;
printf("This program checks if your word is a palindrome.\n");
printf("Enter your word:\t");
scanf("%s", palindroom);
lengte = strlen(palindroom);
for (i = 0; i < lengte; i++)
{
if (palindroom[i] > 64 && palindroom[i] < 91)
{
palindroom[i] = palindroom[i] + 32;
}
if (palindroom[i] != palindroom[lengte - i - 1]) {
woord = 1;
break;
}
}
if (woord) {
printf("Unfortunately, %s is not palindrome\n\n", palindroom);
}
else {
printf("%s is a palindrome!\n\n", palindroom);
}
getchar();
return 0;
}
65 is the decimal representation of A in the ASCII table, 90 is the decimal representation of Z while a is 97 ( = 65 +32 ) and z is 122 ( = 90 +32 )
If you want don't want to use tolower or toupper you can do this:
// tolower
char c = 'U';
char lower_u = c | 0x20
// toupper
char c = 'u';
char upper_u = c & 0xdf
In ASCII the difference between a lower and an upper character is the 5th bit.
When The 5th bit is 0, you get an upper character, when the 5th bit is 1, you get a lower character.

How to find the length of an input

i am trying to measure how many numbers my input has.
if i input the following line: 1 2 65 3 4 7,
i want the output to be 8.but what I'm getting is 1 2 3 4.
#include <stdio.h>
int main(void) {
int data;
int i = 1;
while (i <= sizeof(data)) {
scanf("%d", &data)
printf("%d", i);
i++;
}
}
You are printing i which have no relation to the input at all. So no matter what your input is, you'll get 1234
sizeof(data) is the same as sizeof(int), i.e. a constant with value 4 on your system.
If you want to count the number of numbers and don't care about the value of the individual number, you could do:
#include <stdio.h>
#include <ctype.h>
int main(void) {
char s[1024];
char* p;
int i = 0;
fgets(s, 1024, stdin);
p=s;
while (*p != '\0')
{
if (!isdigit(*p))
{
p++;
}
else
{
i++; // Found new number
// Search for a delimiter, i.e. skip all digits
p++;
while (*p != '\0' && isdigit(*p))
{
p++;
}
}
}
printf("We found %d numbers", i);
return 0;
}
Output:
We found 6 numbers
Notice that this code will accept any non-digit input as delimiter.
put the scanf before the while-loop and move the printf after the while-loop.
I'm also providing solution according to my openion.
#include <stdio.h>
int main(void) {
int data = 1;
int i = 0;
// here data != 0 is trigger point for end input,
// once you done with your inputs you need to last add 0 to terminate
while (data != 0) {
scanf("%d", &data)
printf("Collected Data: %d", data);
i++;
}
printf("Total number of inputs are %d.", i);
}
Hope this solution helps you.
Here is my solution:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i = 0;
int data[100]; // creating an array
while(1) { // the loop will run forever
scanf("%d", &data[i]);
if (data[i] == -1) { //unless data[i] = -1
break; // exit while-loop
}
i++;
}
printf("%d\n", data[2]); // print 2nd integer in data[]
return 0;
}
Do not forget to hit enter once you entered an int. Output of the program:
2
56
894
34
6
12
-1
894
Hope that helps. :)

Add a number to an ascii string in C language

I have a string in C and I need to add +1 to every character in the string. For example, I want abc def to become bcd efg. I want to run it as abc def | ./myprog
This is the code I have, and I can't seem to figure out what the problem is:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
char stringline[200];
char result[200];
int lengthofstr;
int i;
scanf("%s", &stringline);
lengthofstr = strlen(stringline);
for(i=0; i < stringline; i++) {
stringline[i] = (stringline[i] + 1);
}
printf("%s", stringline);
return 0;
}
Looks like a typical typo. Replace
for(i=0;i<stringline;i++){
with
for(i=0;i<lengthofstr;i++){
Compare with the length of the string, not with the array itself
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]){
char stringline[200];
int lengthofstr;
int i;
scanf("%199s", &stringline);
lengthofstr = strlen(stringline);
for(i=0;i<lengthofstr;i++){ // Modify HERE
stringline[i] = (stringline[i] + 1);
}
printf("%s", stringline);
return 0;
}
You were comparing with a pointer which will always be true
Rather than complicating the logic with scanf and format specifiers, etc., you could just read a character at a time from stdin and add '1' if it is an alphabetical character. Try:
#include <stdio.h>
#define MAXC 200
int main (void) {
int c;
int idx = 0;
char result[MAXC] = {0};
while ((c = getchar()) != '\n' && c != EOF && idx < MAXC) {
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) c++;
result[idx++] = c;
}
printf ("\n result: %s\n\n", result);
return 0;
}
Output
$ echo "abc def" | ./bin/stdinplus1
result: bcd efg
It also has the added benefit of leaving non A-Za-z characters unchanged:
$ echo "abc/def*g = hij" | ./bin/stdinplus1
result: bcd/efg*h = ijk

Fixing a letter frequency analyser in C

I'm new to programming and I need some help in getting my program to work because I am kind of stuck at the moment. It's suppose to count the frequency of a letter and other characters for an input text file then print out the results but nothing happens when I do insert a file (but it does compile). This is what I have so far. I think its because I don't return the results of the array back into the main function so it can print out, but I am not sure how to do this. Would you need to use malloc (e.g. int *alphabetCount = (int *)malloc(sizeof(int)*ALPHABET_SIZE);) for the array then free it later?
Any help would be appreciated!
#include <stdio.h>
#include <stdlib.h>
#define ALPHABET_SIZE 26
#define FIRST_LC_LETTER 'a'
#define LAST_LC_LETTER 'z'
#define FIRST_UC_LETTER 'A'
#define LAST_UC_LETTER 'Z'
int freqAnalysis (int inputChar);
int main (int argc, char *argv[]) {
int inputChar = getchar();
int position = 0;
char alphabet [ALPHABET_SIZE] = {'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int alphabetCount [ALPHABET_SIZE];
freqAnalysis (inputChar);
while (position < ALPHABET_SIZE) {
printf ("Letter %c: %d\n",alphabet[position],alphabetCount[position]);
position++;
}
return EXIT_SUCCESS;
}
int freqAnalysis (int inputChar) {
int counter;
int numbers;
int spaces;
int specialChar;
int alphabetCount [ALPHABET_SIZE];
while (counter < ALPHABET_SIZE) {
counter = 0;
alphabetCount [counter] = 0;
counter ++;
}
while (inputChar != EOF) {
if (inputChar >= FIRST_LC_LETTER && inputChar <= LAST_LC_LETTER) {
alphabetCount [inputChar - FIRST_LC_LETTER] ++;
} else if (inputChar>=FIRST_UC_LETTER && inputChar<=LAST_UC_LETTER) {
alphabetCount [inputChar - FIRST_UC_LETTER] ++;
} else if (inputChar >= 0 && inputChar <= 9) {
numbers = 0;
numbers ++;
} else if (inputChar == ' ') {
spaces = 0;
spaces ++;
} else {
specialChar = 0;
specialChar ++;
}
}
printf ("Numbers: %d\nSpaces: %d\n Special characters: %d\n", numbers,
spaces, specialChar);
}
Here is a similar approach to consider. It has been written to remove dependencies from all libc header files except stdio.h. Rather than calling the character classification functions in ctype.h it relies on the ASCII values for each of the characters to set the alphabetCount indexes. Neither approach is better/worse than the other, they just illustrate different ways of approaching the same problem with the various tools available.
#include <stdio.h>
#define ALPHABET_SIZE 26
void freqAnalysis (FILE *fp, int *cnt);
int main (void)
{
int position = 0;
char *alphabet = "abcdefghijklmnopqrstuvwxyz";
int alphabetCount[ALPHABET_SIZE] = {0};
printf ("\nThe frequency analysis of the input characters:\n\n");
freqAnalysis (stdin, alphabetCount);
for (position = 0; position < ALPHABET_SIZE; position++)
printf (" %c/%c : %d\n", alphabet[position] - 32,
alphabet[position], alphabetCount[position]);
return 0;
}
void freqAnalysis (FILE *fp, int *cnt)
{
int c, numbers, spaces, specialChar;
c = numbers = spaces = specialChar = 0;
while ((c = fgetc (fp)) != '\n' && c != EOF)
{
if (c >= 'A' && c <= 'Z')
cnt[c - 'A']++;
else if (c >= 'a' && c <= 'z')
cnt[c - 'a']++;
else if (c >= '0' && c <= '9')
numbers++;
else if ( c == ' ' )
spaces++;
else
specialChar++;
}
printf (" Numbers : %d\n Spaces : %d\n Special : %d\n\n", numbers, spaces, specialChar);
}
Output
$ ./bin/charcount <<<"The Quick Brown Fox Jumps Over 1001 Lazy Dogs."
The frequency analysis of the input characters:
Numbers : 4
Spaces : 8
Special : 1
A/a : 1
B/b : 1
C/c : 1
D/d : 1
E/e : 2
F/f : 1
G/g : 1
H/h : 1
I/i : 1
J/j : 1
K/k : 1
L/l : 1
M/m : 1
N/n : 1
O/o : 4
P/p : 1
Q/q : 1
R/r : 2
S/s : 2
T/t : 1
U/u : 2
V/v : 1
W/w : 1
X/x : 1
Y/y : 1
Z/z : 1
policy of modified to be processed by passing a file handle and an secured array in main.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define ALPHABET_SIZE 26
#define FIRST_LC_LETTER 'a'
#define FIRST_UC_LETTER 'A'
void freqAnalysis(FILE *fin, int counter[]);
int main (int argc, char *argv[]) {
int position;
char alphabet[ALPHABET_SIZE] = {'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};//unused
int alphabetCount[ALPHABET_SIZE] = {0};
freqAnalysis(stdin, alphabetCount);
for (position = 0; position < ALPHABET_SIZE; position++){
printf ("Letter %c: %d\n", alphabet[position], alphabetCount[position]);
}
return EXIT_SUCCESS;
}
void freqAnalysis(FILE *fp, int alphabetCount[]) {
int inputChar;
int numbers , spaces, specialChar;
numbers = spaces = specialChar = 0;
while((inputChar=fgetc(fp)) != EOF) {
if(islower(inputChar)){
alphabetCount[inputChar - FIRST_LC_LETTER]++;
} else if(isupper(inputChar)) {
alphabetCount[inputChar - FIRST_UC_LETTER]++;//this relies on order of character codes.
} else if(isdigit(inputChar)) {
numbers++;
} else if(inputChar == ' ') {//isspace(inputChar)
spaces++;
} else {
specialChar ++;
}
}
printf("Numbers: %d\nSpaces: %d\nSpecial characters: %d\n", numbers,
spaces, specialChar);
}

Resources