Remove the last comma from c loop - c

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

Related

Printing array as sub blocks

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.

How to stop the loop after printing one?

So here is the problem: Write a program that accept an integer n, print out the largest number but smaller or equal n that is the product of two consecutive even number. Example: Input: 12, Output: 8 ( 2x4 )
Here is my code :
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= n; j = j + 2)
{
if ( i == j * (j+2) )
{
printf("%d ", i);
break;
}
}
}
return 0;
}
So if i input 20, it will print out 8 and 0 instead of 8, if i input 30, it will print out 24,8 and 0 instead of just 24. How do i make it stop after printing out the first number that appropriate ?
You need to stop an outer loop from processing, for example by using a boolean flag (meaning "solution found, we finish work") or a goto statement.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int solutionFound = 0;
for (int i = n; i >= 0; i--) {
// this could also be put into for's condition i.e. "i >= 0 && !solutionFound"
if (solutionFound) {
break;
}
for (int j = 0; j <= n; j = j + 2) {
if ( i == j * (j+2) ) {
printf("%d ", i);
solutionFound = 1;
break;
}
}
}
return 0;
}
EDIT: immediate return as noted in the comments is also a nice idea, if you don't need to do anything later.
Your problem is that you are nested - in a for loop which is inside another for loop - when you want to stop processing.
Some languages would let you code break 2; to indicate that you want to break out of 2 loops. Alas, C i snot such a language.
I would recommend that you code a function. That would serve a few porpoises: 1) your main should be "lean & mean" 2) as your programs get larger, you will learn the benefits of putting individual coding tasks into functions 3) you can use return; instead of break; and it will exit the function immediately.
Something like this:
#include <stdio.h>
void FindNeighbouringDivisors(int n)
{
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= n; j = j + 2)
{
if ( i == j * (j+2) )
{
printf("%d times %d = %d", j, j + 2, i);
return;
}
}
}
printf("There are no two adjacent even numbers which can be multiplied to give %d", n);
}
int main()
{
int n;
scanf("%d", &n); /* could get from comamnd line */
FindNeighbouringDivisors(n);
return 0; /* should be EXIT_SUCCESS */
}
Btw, when you have a problem with your code, ask a question here. When you have it working, consider posting it at our code review site where more experienced programmers can give you advice on how to improve it. It's a great way to learn
Break only breaks you out of immediate loop, so either use flags or just use return to terminate the execution. Or you can even use following code:
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int j = 0; j <= n; j = j + 2)
{
if ( n < j * (j+2) )
{
printf("%d ", j*(j-2));
break;
}
}
return 0;
}

Why does my function manage to convert binary to decimal on its own, but not when called in another function?

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.

Comparing numbers inside of an array

Values are entered into an array by the user and then i have this For Loop to compare the numbers once they have all been entered. What i'm trying to do is find the first larger number in the array.
i = 0;
next = a[++i];
for (i = 0; i < len; i++)
{
if (a[i] > a[next])
{
++next;
if (a[i] < a[next])
{
printf("%d is the first larger number.", a[i]);
}
}
}
When I debug my program I see that when "i" is being compared to a[next] its not taking the value of the number inside that position "i" of the array. i've attempted using "i" instead of a[i] when starting my If statements but that doesn't seem to fix the issue.
Here is my Corrected code. made a few more minor changes just for practice
#include <stdio.h>
int main(int argc, const char * argv[])
{
const int len = 4;
int a[len];
int i;
int j = a[i-1];
for (i = 0; i < len; i++) {
printf("Enter a number:");
scanf("%d", &a[i]);
}
i = 0;
for (i = 1; i < len; i++) {
if (a[i] > a[j])
{
printf("%d is the first larger number.", a[i]);
break;
}
}
}
I think you're looking for the first place where the array is not decreasing; i.e., the index of the first element i such that a[i] > a[i-1].
for (i = 1; i < len; i++) {
if (a[i] > a[i-1]) {
printf("%d is the first larger number", a[i]);
break;
}
}
A new version, printing out the first part of the sequence:
for (i = 1; i < len; i++) {
if (a[i] > a[i-1]) {
printf("\n%d is the first larger number", a[i]);
break;
}
printf("%d ", a[i]);
}
Whatever what you are trying to achieve!! you never say:
next = a[++i];
than
a[i] > a[next] !! a[next] can be beyond the size of your array
EX:
A[] = {0, 7, 2, 3, 1}
next = A[1] = 7
A[next] = A[7] = !! //what u think it is?
Assuming that you are looking for the first local maximum, one solution is to declare a variable called best to keep track of the largest number seen so far. Set best to the first element of the array a[0]. Then check for the first element of the array that is less than best.
best = a[0];
for ( i = 1; i < len; i++ )
{
if ( a[i] > best )
best = a[i];
else if ( a[i] < best )
break;
}
printf( "%d is the first larger number.\n", best );

C, Showing count of repeating symbols

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

Resources