Need to figure out a code that counts all the repeating symbols in a string. As you can see below, so far so good.
And here starts the tricky part, at the end of the code I want to output symbols in an order they were typed which had for example 2 occurences in a string, and I got problems figuring that out.
int counts[256] = { 0 };
int i;
size = strlen(text);
for (i = 0; i < size; i++) {
counts[(int)(text[i])]++;
}
for (i = 0; i < 256; i++) {
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
Just iterate through the source string again and for each character look into your counts array.
If you don't want to print the same statistics for every occurence of repeating character, you can reset the corresponding counts value to zero just after you print the statistics, and have an additional check before printing.
for(i = 0; i < size; i++) {
if(counts[(int)(text[i])] == 2)
printf("%d", (int)(text[i]));
The first line loops through your source string for the order of occurences.
The second line checks if it was captured in the counts array as occuring only twice.
If it was we print the char code on the third line.
To only print the character once:
for(i = 0; i < size; i++) {
if(counts[(int)(text[i])] == 2) {
printf("%d", (int)(text[i]));
counts[(int)(text[i])] = 0;
}
}
Here is an implementation of Inspired's answer:
int counts[256] = { 0 };
char text[] = "Hello, world!";
int i, size = strlen(text);
for (i = 0; i < size; i++)
{
counts[(unsigned int)(text[i])]++;
}
for (i = 0; i < size; i++)
{
if (counts[(unsigned int)text[i]] > 1)
{
printf("%c", text[i]);
counts[(unsigned int)text[i]] = 0; // Remove to print repeats.
}
}
Make a key,count pair, like:
#include <string.h>
#include <stdio.h>
int main()
{
char* text = "count this text";
char *keys = new char[strlen(text)];
int* count = new int[strlen(text)];
int last = 0; int j=0;
for(int i=0; i<strlen(text); i++){
for(j=0; j<last; j++){
if(keys[j]==text[i]) break;
}
if(keys[j]==text[i]){
count[j]++;
} else {
keys[last]=text[i];
count[last]=1;
last++;
}
}
for(int i=0; i<last; i++){
printf("%c %d\n", keys[i], count[i]);
}
}
so you keep the order in the text and get the count.
On execution the output is:
c 1
o 1
u 1
n 1
t 4
2
h 1
i 1
s 1
e 1
x 1
Related
i have the belowo loop in c that print the prime number
for(int i = 2; i<=arraySize; i++)
{
//If arraySize is not 0 then it is prime
if (numbers[i]!=0)
printf("%d,",numbers[i]);
}
the out put after enter 50 for example is
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
i want to to not print the last comma how i can do it
i tried this code but not working
printf("%d%s", numbers[i], (i !=arraySize-1) ? "," : "");
Instead of printing a comma after each number, print it before. Then you can use a variable to tell if this is the first number being printed, and not print the comma.
first=true;
for(int i = 2; i<=arraySize; i++)
{
//If numbers[i] is not 0 then it is prime
if (numbers[i]!=0) {
printf("%s%d", (first ? "" : ","), numbers[i]);
first = false;
}
}
I like both the other answers but just want to throw in this error prone variant on the same theme.
_Bool first = true;
for (int i = 2; i <= arraySize; i++) {
if (numbers[i] != 0) {
printf(",%d" + first, numbers[i]);
first = false;
}
}
If first is true the actual formatting string will become "%d". If it's false it'll become ",%d".
Simple: Use a pointer to the "prefix" string, printed AHEAD of the next value:
char *sep = "";
for(int i = 2; i <= arraySize; i++ ) {
if( numbers[i] ) {
printf( "%s%d", sep, numbers[i] );
sep = ", "; // I added a SP, too
}
}
Here's an alternative that uses a "limited scope" variable to index a static string. For clarity in this example, the array boundaries have been adjusted.
int main( void ) {
int numbers[] = { 1, 1, 4, 8, 9, 0, 7 };
int arraySize = sizeof numbers/sizeof numbers[0];
for( int i = 0, out = 0; i < arraySize; i++ )
if( numbers[i] )
printf("%s%d", &","[!out++], numbers[i] );
return 0;
}
The negated boolean post-incrementing value of out provides the address of the '\0' to the first instance, then the address of "," in subsequent instances.
1,1,4,8,9,7
The answers already here are fine, but I'd like to add a "simpler" solution. Simpler in that it doesn't require any further logic or extra variables. It does, however, require that you know that the first number is non-zero.
printf("%d", numbers[2]);
for (int i = 3; i < arraySize; i++)
{
if (numbers[i] != 0)
printf(",%d", numbers[i]);
}
I think the other answers overcomplicates things. I don't see any reason to have a test for every iteration in the loop. Instead, I'd simply do the special case first:
printf("%d", numbers[2]);
for (int i = 3; i <= arraySize; i++) {
if (numbers[i]!=0)
printf(",%d", numbers[i]);
}
This will however need some additional code to correctly handle the case where arraySize is lower than 3.
But I would choose another approach from the beginning, and that is writing a good function for printing an array. Could look like this:
void printArray(const int *array, int size) {
putchar('['); // Of course this is optional
if(size > 0) {
printf("%d", array[0]);
for(int i=1; i<size; i++)
printf(",%d", array[i]);
}
putchar(']'); // And this too
}
and then something like this:
int convertArray(const int *numbers, int *array, int size) {
int ret = 0;
for(int i=0; i<size; i++) {
if(number[i] != 0) {
array[ret] = numbers[i];
ret++;
}
}
return ret;
}
I have array and I am trying to print this array as sub blocks, where each block has size = 5.
the out put of this code not as I expected it just print the first 5 values. How to print the array as sub blocks?
int arr[298] = {some int values};
int in = 0;
int siz = 298;
int ii;
int rang = 5;
for (int i = 0; i < siz; i++) {
if (in <= siz) {
for (ii = in; ii < 5; ii++) {
printf("arr=%d \n", arr[ii]);
}
printf("------------\n");
}
ind = ind + rang;
}
Following your request for clarification in the comment section, there are a few problems with your code, for me the biggest one is that it's needlessly complicated, but the one you are looking for is in this line:
ind = ind + rang;
ind is is not declared in your code but I assume you mean in, the first time the inner loop runs in(ind) is 0 so it all goes well, after that in will be 5, you assign it to ii and the condition ii < 5 will never be true again, the body of the loop will never be executed.
I suppose you could fix it by using in as index for the array and scrap rang since it isn't needed, something like this:
int arr[298] = {some int values};
int in = 0;
int siz = 298;
for (int i = 0; i < siz; i++) {
//if (in < siz) { moving this into the for loop
for (int ii = 0; ii < 5 && in < siz; ii++, in++) {
printf("arr=%d \n", arr[in]);
}
printf("------------\n");
//}
}
Live demo: https://godbolt.org/z/YzG9sno1n
But you don't need a nested loop, there are a few ways you can do this, a simple one is to have a variable that controls the block size:
int arr[298] = {some int values};
int siz = 298;
int count = 5;
for (int i = 0; i < siz; i++) {
printf("arr=%d \n", arr[i]);
count--;
if (count == 0) {
printf("------------\n");
count = 5;
}
}
Live demo: https://godbolt.org/z/b4e8vWfhM
In the above code count serves as the control variable, the value in the index is printed 5 times and when it reaches 0 a separator is printed and it resets and starts the new block.
Another possible option is to use the index itself to separate the blocks, you know the remainder of a division is 0 when the numerator is divisible by the denominator, you can use that to your advantage:
int arr[298] = {some int values};
int siz = 298;
for (int i = 0; i < siz; i++) {
if (i % 5 == 0) { // && i != 0 if you want to skip the initial separator
printf("------------\n");
}
printf("arr=%d \n", arr[i]);
}
Live demo : https://godbolt.org/z/nne3z38rY
Finally you can/should use a constant value for size:
#include <stdio.h>
#define SIZE 298
int main() {
int arr[SIZE] = {some int values};
for (int i = 0; i < SIZE; i++) {
if (i % 5 == 0 && i != 0) { // skipping the initial separator
printf("------------\n");
}
printf("arr=%d \n", arr[i]);
}
}
Live demo: https://godbolt.org/z/Mc4Yh4cav
Instead of several for loops, you can use a single while loop.
int arr[298 ]={Some int Values};
int ind =0;
int siz= 298 ;
printf("------------\n");
while(ind<=siz-1){
printf("arr=%d \n",arr[ind]);
ind++;
if(ind%5==0){
printf("------------\n");
}
}
In this, you print the elements through 0 to 297, with a line of dashes printed if the index is divisible by 5, that is after every fifth element.
I'm writing a program that calls upon a function applyS() which calls upon a function binaryToDecimal() which converts a char[] filled with 1s and 0s into an integer.
binaryToDecimal() works when i test it on its own.
The char[] which it gets in applyS() is properly filled with the 1s and 0s it should have.
Still, binaryToDecimal() outputs only 0s. Only in the first conversion it outputs a 2, which is still incorrect.
binaryToDecimal() looks like this.:
void binaryToDecimal(char binary[], int *decimal, int binLength)
{
*decimal = 0;
for (int i = 0; i < binLength; i++)
{
int currentPos = binLength - i - 1;
if (binary[currentPos] == 0 || binary[currentPos] == 1)
{
*decimal += binary[currentPos]*pow(2,i);
}
else
{
printf("Illegal input. Can't convert to decimal.");
}
}
}
applyS() looks like this:
void applyS(char sTable[][16], char inputBlock[], char outputBlock[])
{
char splitBefore[8][6];
char splitAfter[8][4];
splitForS(inputBlock, splitBefore);
for (int i = 0; i < 8; i++)
{
int rowArray[2];
int row;
int columnArray[4];
int column;
int newBlockDecimal;
rowArray[0] = splitBefore[i][0];
rowArray[1] = splitBefore[i][5];
columnArray[0] = splitBefore[i][1];
columnArray[1] = splitBefore[i][2];
columnArray[2] = splitBefore[i][3];
columnArray[3] = splitBefore[i][4];
for (int j = 0; j < 2; j++)
{
printf("%d", rowArray[j]);
}
printf(" ");
for (int j = 0; j < 4; j++)
{
printf("%d", columnArray[j]);
}
binaryToDecimal(rowArray, &row, 2);
printf("\t%d ", row);
binaryToDecimal(columnArray, &column, 4);
printf("%d ", column);
printf("\n");
/*newBlockDecimal = sTable[row][column];
decimalToBinary(newBlockDecimal, splitAfter[i], 4);*/
}
joinAfterS(splitAfter, outputBlock);
}
My output is this:
Thank You for helping, I found the mistake.
In applyS() rowArray[] and charArray[] are integer arrays, they should be character arrays.
I have an array with 100 numbers in it, and I am trying to print it out with only 10 ints on each line, and a tab between each number. It is only printing the first 10 integers and then stopping, which makes sense because of my for loop. I am clearly missing part of it to allow for it to continue through the array. I was going to try to add the line
for(int line_num = 0; line_num < 10; line_num+=10)
before the for statement after the while loop
int array_value;
int length_of_array = 100;
while (length_of_array <= 100){
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
I was also thinking of including a line like
if (array_value % 10 == 0)
printf("\n");
I figured it out! Posted the answer below.
This might be what you're looking for:
/* test.c */
#include <stdio.h>
#define ELEMENTS 100
int main (void)
{
int array [ELEMENTS];
for ( int i = 0; i < ELEMENTS; ++i )
array [i] = i;
for ( int i = 0; i < ELEMENTS; ++i ) {
printf ("%i", array[i]);
if ( (i + 1) % 10 != 0 )
printf ("\t");
else
printf ("\n");
}
return 0;
}
edit: Because of the way the tab can extend to the next line at the end of the line you have to be careful with the tab and new line character.
For clarity, rename length_of_array to offset_in_array and then set it to zero at the start. I renamed array_value and corrected your length check. I also added a check to the inner loop in case the array length gets changed and doesn't divide by 10.
Something like:
int i;
#define ARRAY_LENGTH 100
int offset_in_array = 0;
while (offset_in_array < ARRAY_LENGTH){
for(i = 0; i < 10 && offset_in_array < ARRAY_LENGTH; ++i){
printf("%d ", A[offset_in_array]);
++offset_in_array;
}
}
I haven't tried running this but it should be closer.
Just print a newline every tenth number... If it's not a tenth number, then print a tab.
for (size_t i = 0; i < array_length; ++i) {
printf("%d%c", A[i], i % 10 != 9 ? '\t' : '\n');
}
Live code available at onlinedbg.
Just change the value of length_of_array to 0 and print \n after a for loop.
int array_value;
int length_of_array = 0;
while (length_of_array <= 100) {
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
printf("\n");
}
You can use the following solution to print 10 lines of 100 array values in C:
for (int i = 0; i < 100; ++i){
printf("%i\t", A[i]);
if ((i+1)%10 == 0){
printf("\n");
}
}
int main(void)
{
int i,j=0,k; //initialization
char equation[100]; //input is a string (I think?)
int data[3]; //want only 3 numbers to be harvested
printf("Enter an equation: ");
fgets(equation, 100, stdin); //not so sure about fgets()
for (i = 0; i < equation[100]+1; i++) { //main loop which combs through
//"equation" array and attempts
//to find int values and store
while (j <= 2) { //them in "data" array
if (isdigit(equation[i])) {
data[j] = equation[i]
j++;
}
}
if (j == 2) break;
}
for (k = 0; k <= 2; k++) { //this is just to print the results
printf("%d\n", data[k]);
}
return 0;
}
Hello! This is my program for my introductory class in C, I am trying to comb through an array and pluck out the numbers and assign them to another array, which I can then access and manipulate.
However, whenever I run this I get 0 0 0 as my three elements in my "data" array.
I am not sure whether I made an error with my logic or with the array syntax, as I am new to arrays.
Thanks in advance!!! :)
There are a few problems in your code:
for (i = 0; i < equation[100]+1; i++) { should be something like
size_t equ_len = strlen(equation);
for (i = 0; i < equ_len; i++) {
Whatever the input is, the value of equation[100] is uncertain, because char equation[100];, equation only has 100 element, and the last of them is equation[99].
equation[i] = data[j]; should be
data[j] = equation[i];
I suppose you want to store digit in equation to data.
break; should be deleted.
this break; statement will jump out of the while loop, the result is you will store the last digit in equation to data[0] (suppose you have switched data and equation, as pointed out in #2).
If you want the first three digits in equation, you should do something like
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
printf("%d\n", data[k]); should be printf("%c\n", data[k]);
%d will give the ASCII code of data[k], for example, if the value of data[k] is character '1', %d will print 50 (the ASCII code of '1') instead of 1.
Here is my final code, based on the OP code:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int i,j,k;
char equation[100];
int data[3];
int equ_len;
printf("Enter an equation: ");
fgets(equation, 100, stdin);
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
for (k = 0; k <= 2; k++) {
printf("%c\n", data[k]);
}
return 0;
}
Tested with:
$ ./a.out
Enter an equation: 1 + 2 + 3
1
2
3