Remove white space at the end of the output in C - c

The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the online compiler against which I'm checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?
For reference, my code is as follows (yes the variable names are terrible. I'm working on changing my habit of putting random variable names!!)
#include <stdio.h>
int main()
{
int a[6][6];
int i, k = 0, l = 0, m=3, n=3, j;
scanf("%d %d",&m, &n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
while (k < m && l < n)
{
for (i = l; i < n; ++i)
printf("%d ", a[k][i]);
k++;
for (i = k; i < m; ++i)
printf("%d ", a[i][n-1]);
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
printf("%d ", a[m-1][i]);
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
printf("%d ", a[i][l]);
l++;
}
}
return 0;
}
Input:
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5{one extra space}
Any way to fix this problem?
(Also sorry for the terrible formatting. First question on StackOverflow!)

You can put an if condition in your for loops
for (i = l; i < n; ++i)
{
printf("%d", a[k][i]);
if(i < n-1)
printf(" ");
}

You need to suppress the space when you don't need one.
You can do it like this:
Add these declarations:
char *format = "%d";
int first_number = 1;
Add this after the first printf:
if (first_number) {
/* Now we want a space between numbers */
first_number = 0;
format = " %d";
}
Change your printf:s to use the new variable:
printf(format, ...);

Looking at your code, this for (the first one in the while loop):
for (i = l; i < n; ++i)
printf("%d ", a[k][i]);
will always be executed at least ones (because l<n, coming from the while's condition).
Then you can just do the following:
always add the space in front of the number
add a single if check just for this very first for-loop (use some bool flag).
For example, something like:
bool first = true;
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
if( ! first )
{
printf(" %d", a[k][i]);
}
else
{
printf("%d", a[k][i]);
first = false;
}
}
// ....
}
This will be rather efficient and short solution - the if is in just one loop and the flag will be true just once (will avoid cache misses).

You can set a boolean variable isFirst to true before your printing out any stuff, and test it before each printf statement. If isFirst, do not print a space but set isFirst to false; else print a single space. After that, continue with printing your number without a space.
Alternative: Instead of printing your results immediately, create a results array. Store your results in there, and when done, print out the results in a tight loop. You can print the first number without a leading space, then loop over the remainder and print them with a leading space.

the printf() statement,
printf("%d ", a[k][i]);
results in extra space. use
"%d"
without space or use space in the begining as,
" %d"
then at the end there wont be a extra space.
its about how you use space in your printf(). use space in a way that extra space is not present at the end as you wanted.
You can use code like this,
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
if(l==0&&i==0)
{
printf("%d", a[k][i]);
}
else
printf(" %d", a[k][i]);
}
k++;
for (i = k; i < m; ++i)
printf(" %d", a[i][n-1]);
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
printf(" %d", a[m-1][i]);
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
printf(" %d", a[i][l]);
l++;
}

An answer after accepted answer:
Rather than:
while (k < m && l < n) {
...
printf("%d ", a[k][i]);
...
printf("%d ", a[i][n-1]);
...
printf("%d ", a[m-1][i]);
...
printf("%d ", a[i][l]);
...
}
Change the format.
const char *format = "%d";
while (k < m && l < n) {
...
printf(format, a[k][i]);
format = " %d";
...
printf(format, a[i][n-1]);
...
printf(format, a[m-1][i]);
...
printf(format, a[i][l]);
...
}
fputc('\n', stdout); // if desired.

Related

Why am I experiencing an infinite loop here?

My code never stops asking for input so I think I must've made an infinite loop, but I can't find where the error is. I've also noticed that when inserting the input line by line, it prints the result of one loop after inserting the first line of the second loop, which seems incorrect to me. Please help me debug. (For further context, the code is supposed to receive a number we'll call n, and then scan 3n more lines, which are basically n bundles of 3 similar lines. The 2nd and 3rd lines are two words with the same num of characters, and the 1st line is that num. The output is whether or not these words are anagrams.)
#include <stdio.h>
int main() {
int n, l;
scanf("%d\n", &n);
for (int i = 1; i <= n; i++) {
scanf("%d\n", &l);
char A[l], B[l];
for (int j = 0; j < l; j++) {
scanf("%c", &A[j]);
scanf("\n");
}
for (int j = 0; j < l; j++) {
scanf("%c", &B[j]);
scanf("\n");
}
for (int k = 0; k < l; k++) {
int result = 0;
for (int j = 0; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
}
}
Example:
input:
2
6
listen
silent
4
Evil
live
output:
YES
NO
It's because you are asking for input over and over and over again,
Not sure what you are trying to achieve, but start by removing the extra scanfs
try this,
#include <stdio.h>
int main() {
int n, l;
scanf("%d\n", &n);
for (int i = 1; i <= n; i++) {
char A[l], B[l];
for (int k = 0; k < l; k++) {
int result = 0;
for (int j = 0; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
}
}
Your scanf calls wait for an extra \n which requires more input to enter.
To fix this, remove the \n from your scanf calls. Also remove the extra calls when you enter A and B:
I have added some debug code to demonstrate where you are in your program execution while you enter your input.
#include <stdio.h>
int main() {
int n, l;
int res;
res=scanf("%d", &n);
printf ("res=%d, n=%d\n", res, n);
for (int i = 1; i <= n; i++) {
res = scanf("%d", &l);
printf ("res=%d, l=%d\n", res, l);
// char A[l], B[l];
char A[l+1], B[l+1];
for (int j = 0; j < l; j++) {
scanf(" %c", &A[j]);
}
printf ("A done\n");
for (int j = 0; j < l; j++) {
scanf(" %c", &B[j]);
}
printf ("B done\n");
A[l] = 0; B[l] = 0;
printf ("A=\"%s\" - B=\"%s\"\n", A, B);
...
Now your input should work properly.
But your code also contains another error.
You will treat "12344" and "11234" as correct match wchich is wrong.
To fix this you need to remove each matching character from B:
for (int k = 0; k < l; k++) {
int result = 0;
// We compare A[k] with the remaining characters in B only
for (int j = k; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
B[j] = B[k]; // Replace matching character with non-matching character we checked earlier.
break;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
This code stops as soon as the first match is found and removed that character from B.
The entries in B are rearranged to keep the unused entries at the end.
The full code looks like this:
#include <stdio.h>
int main() {
int n, l;
int res;
res=scanf("%d", &n);
printf ("res=%d, n=%d\n", res, n);
for (int i = 1; i <= n; i++) {
res = scanf("%d", &l);
printf ("res=%d, l=%d\n", res, l);
// char A[l], B[l];
char A[l+1], B[l+1];
for (int j = 0; j < l; j++) {
scanf(" %c", &A[j]);
}
printf ("A done\n");
for (int j = 0; j < l; j++) {
scanf(" %c", &B[j]);
}
printf ("B done\n");
A[l] = 0; B[l] = 0;
printf ("A=\"%s\" - B=\"%s\"\n", A, B);
for (int k = 0; k < l; k++) {
int result = 0;
for (int j = k; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
B[j] = B[k];
break;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
}
}
output:
~/stackoverflow$ ./test
4
res=1, n=4
2
res=1, l=2
12
A done
21
B done
A="12" - B="21"
YES
6
res=1, l=6
liver1
A done
evil1r
B done
A="liver1" - B="evil1r"
YES
3
res=1, l=3
111
A done
111
B done
A="111" - B="111"
YES
4
res=1, l=4
abcd
A done
dcbb
B done
A="abcd" - B="dcbb"
NO

I want to print out the following to the console

I want to print out the following to the console:
+++++
++++*
+++**
++***
+****
*****
I am a new learner of programming, so encountering some difficulties. Can anyone help me, please? I have tried this, but is incorrect. What do I need to change?
#include<stdio.h>
int main(){
int i, j, k;
for(i=0; i<5; i++){
for(j=i; j<5; j++){
for(k=0; k<j; k++){
printf("*");
}
printf("+");
}
printf("\n");
}
return 0;
}
You have the right idea: Use three for loops.
#include <stdio.h>
int main() {
for (int i = 0; i < 6; i++) {
for (int k = i; k < 5; k++) {
printf("+");
}
for (int j = 0; j < i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Test
+++++
++++*
+++**
++***
+****
*****
Online demo
First, generalise it and wrap it in a function. You want a square with a diagonal. It has to be an even number of characters to look right. But + and * could be any character, and the size could be 6 or all the way up to screen maximum width.
so
/* print a square with a diagonal
N - the size of the sides of the square
cha - character a (eg '+')
chb - character b (eg '*')
*/
void printdiagsquare(int N, char cha, char chb);
That's our prototype, and that's half the battle.
Now we need to check N is even and positive, then write the loops.
Let's get the test away first.
if(N < 2 || (N % 2) == 1)
printf(N must be even\n");
Now the main loop for each line
for(i=0;i<N;i++)
{
//printline code here
printf("\n");
}
Now test it. Is it printing N blank lines?
main(void)
{
printdiagsquare(6, '+', '*');
}
Now to get the lines printed.
to print N-1 '+'s is easy. We need j as the counter since i is the outer
for(j=0;j<N-1;j++)
printf("%c", cha);
But we need to generalise, we need to print 6,, 5, 4, 3 and so on as i increases.
So
for(j=0;j<N-i-1;j++)
printf("%c", cha);
I'll leave the last little bit for you to do. No point just typing ina function blindly.
You could try more optimized code for m-rows and n-columns
in 2 for loop only :-
#include <stdio.h>
int main(void) {
int m = 6; // Rows
int n = 5; // Cols
int i,j,k;
for (i = 0; i < m; i++) {
k = i;
for (j = n; j >= 0; j--) {
if(k>=j)
printf("*");
else
printf("+");
}
printf("\n");
}
return 0;
}

printing grid with specified dimension with n*n

I am trying to create a grid of, for example, 4 rows and 4 columns.The dimension of the grid is n*n size. I have tried the following piece of code which is working fine for 3 rows only as I am trying to print 4*4 grid. But the last grid (4th is this case) is never printed. I mean as soon as the 3rd grid is printed the loop exits. I would appreciate if anyone help me to figure out why it is taking only 3 rows with 4 columns rather than 4 rows with 4 columns? Here is what I have tried so far,
void main()
{
int n, i, j;
scanf("%d", &n);
char grid[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == '9')
printf("X");
else
printf("%c", grid[i][j]);
}
}
}
This is a very quick hack to get your code working, as I believe you expect. Including the \n in scanf is probably not the best way of doing this, please see this answer:
int n, i, j;
scanf("%d\n", &n);
char grid[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == '9')
printf("X");
else
printf("%c", grid[i][j]);
}
printf("\n");
}
Using this as input:
4
1234234534564567
This is the output:
1234
2345
3456
4567
The line
scanf("%c", ...)
will also read any newline chars typed, including the one following the previous
scanf("%d", ...)
So if you enter each line's data followed by a newline, you will have read 1 + 3 * 5 = 16 characters after the third line.
I suggest you input four strings instead, and copy each character to the array, using scanf("%s", ...). That way, all whitespace will be ignored (except the final newline will remain in the input buffer).

garbage value in C array

I am trying to write a C code that will print a pyramid structure on screen, something like this.
The corresponding code I've written is something like this.
#include <stdio.h>
#include <stdlib.h>
void printArrayFunc(char arr[9][5]) {
int i, j;
printf("=========================================\nprinting the values\n");
for (i = 0; i < 5; i++) {
for (j = 0; j < 9; j++) {
//printf("arr[%d][%d] = %d\n", i,j, arr[i][j]);
if (arr[i][j] == 1)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
int main() {
int i, j;
char arr[9][5] = {
0
};
printf("============================\nfilling the values\n");
for (i = 0; i < 5; i++) {
for (j = 4 - i; j <= 4 + i; j++) {
arr[i][j] = 1;
// printf("arr[%d][%d]= %d\n",i,j,arr[i][j]);
}
//printf("\n");
}
printArrayFunc(arr);
return 0;
}
It is giving an output like
I know I'm doing some silly mistake but at this moment, I'm not able to find what is going wrong. Let me hear your comments on this.
In the function argument:
char arr[9][5]
In the loop:
for (i = 0; i<5; i++) {
for (j = 0; j<9;j++) {
if (arr[i][j] == 1)
You flipped the position of i and j. i should go from 0 to 9, j from 0 to 5.
if (arr[i][j] == 1)
printf("*");
else
printf(" ");
This statement is giving the garbage value in this statement if if condition is true then it print else statement and when else comes true it prints the garbage value.

lining up printfs to look nice and line them up

How in the world do you format this for things to line up, ive tried everything, nothing changes?!
printf("N Count\n");
printf("---- ------ \n");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%1d %1d\n", arr[i], count);
}
I've tried tabbing, spacing, those % signs with the numbers for the last one, it wont change from this
N Count
----- ---
1 1
2 1
3 1
Driving me crazy! I dont get it! lol
EDIT WHOLE PROGRAM NEW QUESTION!
#include <stdio.h>
#define MAX_ELEMENTS 10
int getOccur(int a[], int num_elements, int value);
void printArr(int a[], int num_elements);
int main()
{
int arr[MAX_ELEMENTS];
int trim[MAX_ELEMENTS];
int count, target, i;
int j, k, temp;
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
printf("Enter a variable for the array: ");
scanf("%d", &arr[i]);
}
for (j = 1 ; j <= MAX_ELEMENTS-1 ; j++)
{
for(k = 0 ; k <= MAX_ELEMENTS-2 ; k++)
{
if(arr[k] > arr[k+1])
{
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
printf("%4s %6s\n", " N ", "Count");
printf("%4s %6s\n", "----", "------");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%3d %4d\n", arr[i], count);
}
}
int getOccur(int a[], int tally, int value)
{
int i;
tally = 0;
for( i = 0 ; i < MAX_ELEMENTS ; i++)
{
if (a[i] == value)
{
++tally;
}
}
return(tally);
}
void printArr(int a[], int amount)
{
int i;
for(i = 0 ; i < amount ; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
printf("%4s %6s\n", " N ", "Count");
printf("%4s %6s\n", "----", "------");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%4d %6d\n", arr[i], count);
}
That should line everything up.
EDIT
In response to the question in the comments, my approach would be to first find all the unique values in arr and save them to a different array (call it unique). Then you'd walk through the unique array in your loop:
for (i = 0; i < uniqueCount; i++)
{
count = getOccur(arr, MAX_ELEMENTS, unique[i]);
printf("%4d %6d\n", unique[i], count);
}
As for finding unique elements, the brute force method would be something like
size_t uniqueCount = 0;
int unique[MAX_SIZE]; // needs to be same size as original array in case
// all values are unique
for (i = 0; i < MAX_SIZE; i++)
{
size_t j = 0;
for (j = 0; j < uniqueCount; j++)
if (arr[i] == unique[j])
break;
if (j == uniqueCount)
unique[uniqueCount++] = arr[i];
}
For each element in the original array, we scan the (initially empty) unique array. If we don't find the value of a[i] in the unique array, we add it and increment uniqueCount.
Note that this method is pretty inefficient and will perform poorly as MAX_ELEMENTS gets large. Better solutions are available, but you sound like you're still at the bottom of the learning curve, so I'll leave it at that.
This is what you are looking for. The first column you have four - so the minimum width is four, the next column has size - so minimum width is 6 as specified in the format string. see printf manual page
printf("N Count\n");
printf("---- ------ \n");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%4d %6d\n", arr[i], count);
}
EDIT
Edited first printf

Resources