I want to print some C pattern for upper triagnle which sholud print numeric value 1 to 10.
Now my code is like this:-
#include <stdio.h>
int main() {
int j = 1, k, l, i;
for (i = 4; i >= 1; i--) {
for (k = i - 1; k >= 0; k--) {
printf(" ");
}
for (l = 4; l >= i; l--) {
printf("%2d", j);
j++;
}
printf("\n");
}
return 0;
}
Its output is fine but when my value reach near 10 it's space is missing.
How can I resolve it?
My output looks like
1
2 3
4 5 6
7 8 910
It should be:
1
2 3
4 5 6
7 8 9 10
You can change the alignment by using the - sign. This makes it left-justified.
Replace
printf("%2d",j);
with
printf("%-2d",j);
Live demo
If you want the bottom of the pyramid to be completely to the left with no space you can replace
for (k = i - 1; k >= 0; k--)
with
for (k = i - 1; k > 0; k--)
EDIT:
As #chqrlie pointed out this will leave a trailing blank space in every line except the last one, this can be fixed like:
//...
for (i = 4; i >= 1; i--)
{
for (k = i - 1; k > 0; k--) // change from k >= 0 to k > 0
{
printf(" ");
}
for (l = 4; l >= i; l--)
{
printf(" %d", j); // change from "%2d" to " %d"
j++;
}
printf("\n");
}
//...
Live demo
For this problem, with n lines of output, you need to produce n - i spaces at the beginning of line i and i numbers each preceded by a space. Instead of "%2d", use " %d" and output one less space at the start of each line. You can use printf to output an arbitrary number of spaces using %*s and an empty string.
Here is a modified version:
#include <stdio.h>
int main() {
int i; // line number
int j = 1; // starting number
int n = 4; // number of lines
int k;
for (i = 1; i <= n; i++) {
printf("%*s", n - i, ""); // output n - i spaces
for (k = 0; k < i; k++) {
printf(" %d", j);
j++;
}
printf("\n");
}
return 0;
}
Output:
1
2 3
4 5 6
7 8 9 10
It can be solved in two ways:
One way to resolve this is by simply add spacing (padding) for each character you are printing.
#include<stdio.h>
int main()
{
int j=1,k,l,i;
for(i=4;i>=1;i--){
for(k=i-1;k>=0;k--){
printf(" ");
}
for(l=4;l>=i;l--){
printf(" %2d ",j); //Padding added
^ ^
j++;
}
printf("\n");
}
return 0;
}
Secondly you can change the alignment by using - sign
#include<stdio.h>
int main()
{
int j=1,k,l,i;
for(i=4;i>=1;i--){
for(k=i-1;k>=0;k--){
printf(" ");
}
for(l=4;l>=i;l--){
printf("-%2d",j); //Left justified
^
j++;
}
printf("\n");
}
return 0;
}
Amongst the other good answers, another way is to use printf("%d ", j); instead of printf("%2d", j); - Note the white space ' ' behind the %d format specifier. - This method has the disadvantage that you have a trailing white space after 10 but it accomplishes the (obvious) desired output:
Online example
#include <stdio.h>
int main (void)
{
int j = 1, k, l, i;
for (i = 4; i >= 1; i--){
for (k = i - 1; k >= 0; k--) {
printf(" ");
}
for(l = 4; l >= i; l--) {
printf("%d ", j);
j++;
}
printf("\n");
}
return 0;
}
Output:
1
2 3
4 5 6
7 8 9 10
Related
My output of the code is:
1
1 2
3 5 8
13 21 34 55
89 144 233 377 610
My desired output is:
1
1 2
3 5 8
13 21 34 55
89 144 233 377 610
Can you please let me know where do I have to change the code.
#include <stdio.h>
int fib(int);
int main() {
int i, j, k = 1;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", fib(k++));
}
printf("\n");
}
return 0;
}
int fib(int n) {
if (n <= 1)
return n;
return (fib(n - 1) + fib(n - 2));
}
The space between each number is the same in my output, but in the desired output all the elements are properly sorted which makes them appear in the same columns.
Use the following call of printf
printf("%-8d", fib(k++));
^^^^
instead of
printf("%d ", fib(k++));
There are 2 ways to achieve the desired appearance:
you can use TAB as a separator, which will make the numbers aligned on tab stops, usually 8 characters apart on most terminals, but as you can see from how your question appears on stackoverflow, can be 4 characters apart in other places.
you can use the "%-7d " format which pads the number with spaces to its right if it has less than 7 digits, and an extra space to separate it from the next in all cases.
Here is a modified version using printf to align the columns:
#include <stdio.h>
int fib(int);
int main() {
int i, j, k = 1;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) {
printf("%7d ", fib(k++));
}
printf("\n");
}
return 0;
}
int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
Here is a different version using TABs, that produces the expected output:
#include <stdio.h>
int fib(int);
int main() {
int i, j, k = 1;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) {
printf("%d", fib(k++));
if (j < i)
printf("\t");
else
printf("\n");
}
}
return 0;
}
int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
I have problem with my code I need to make. I have to take 14 parameters from command line and use them to make lottery numbers, winning numbers and then compare those 2 with each other.
For example using this parameter: ./a.out 2 30 17 8 6 19 24 7 6 1 2 3 5 4
Should make something like this:
Winning numbers: 2 30 17 8 6 19 24
Lottonumbers: 7 6 1 2 3 5 4
2 are the same: 6 2
My code is almost working as intended, but I can't seem to print this right: 2 are the same. It always loops like this: 1 are the same: 6 2 are the same: 2.
Number 2 is the amount of same numbers that are found when 2 arrays are compared. My question is how can I print it so that it won't duplicate the text and with the right amount? My head can't seem to work even if it's so simple :/
#include <stdio.h>
#include <stdlib.h>
int main(int args, char **argv)
{
int i;
int winningNumbers[7];
int lottoNumbers[7];
int j;
int a;
int b;
int winningNumber;
int lottoNumber;
int count = 0;
printf("Winning numbers: ");
for (i=0;i<7; i++) {
winningNumber = atoi(argv[i+1]);
winningNumbers[i] = winningNumber;
printf("%d ", winningNumber);
}
printf("\n");
printf("Lotto numbers:: ");
for (j= 8; j < args; j++) {
lottoNumber = atoi(argv[j]);
lottoNumbers[j-8] = lottoNumber;
printf("%d ", lottoNumber);
}
printf("\n");
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
printf("%d are the same: %d", count, winningNumbers[b]);
}
}
}
return 0;
}
Searching for matches and displaying the result are two separate tasks. It is simpler and more flexible not to attempt to do them at the same time.
First search for the matches and store them in an array. Then display the content of the array however you want.
int main (int argc, char *argv[])
{
int winningNumbers[7];
int lottoNumbers[7];
int commonNumbers[7];
int count = 0;
// fill winningNumbers
// fill lottoNumbers
// NOTE: the following loop assumes that in both arrays
// no number is repeated.
// You should check that this is indeed the case.
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (lottoNumbers[i] == winningNumbers[j]) {
commonNumbers[count] = lottoNumbers[i];
count++;
}
}
}
printf ("%d are the same:", count);
for (int i = 0; i < count; i++) {
printf (" %d", commonNumbers[i]);
}
printf ("\n");
return 0;
}
Many simple programs should follow this structure:
read and check input
transform input to output
print output
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
}
}
printf("%d are the same: ", count);
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
printf(" %d", winningNumbers[b]);
}
}
printf("\n");
int finalArray[7];
int i;
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
finalArray[count] = lottoNumbers[a];
count = count + 1;
}
}
}
printf("%d are same: ", count);
for(i = 0; i < count; i++)
printf("%d ", finalArray[i]);
I am trying to assign user input into an array; however, the program below only picks up on the first element in each line of input. The ultimate goal of this program is to find the diagonal sums of integers and return the absolute value of their difference.
Example input (note that the first number gives the number of rows and columns (square array):
Input:
3
11 2 4
4 5 6
10 8 -12
Output:
Expected = 15
Actual = 10
I realize that the issue lies in the way that the array is setup. If I print the array out I get: 111555999
Any hints/help would be very appreciated.
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%i", &n); //N = number of rows and number of columns (square 2D array)
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d ", &multi_array[c][i]); //enter integers to store in array
}
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i]; //add up top left to bottom right diagonal
}
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
printf("%i", abs(sum1 - sum2)); //print absolute value of the difference between diagonals
return 0;
}
Your major problem is here, where you go out of bounds:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i]; // when i is 0, th
}
When i = 0, you are accessing multi_array[0][3], which is out of bounds when N = 3.
So change it to this:
multi_array[i][n - i - 1]
You should read your array like this:
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf(" %d ", &multi_array[i][c]);
}
}
since C stored its arrays in row-major order. What you have stores the array in column-major order. It's not wrong, but it's something you do only if you really have to.
Finally, change again the input part of your code to this:
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
so that you have to input exactly what you need to. With your initial code I have to type an extra random number when I had completed the input process.
Last but not least, I am posting the whole code, where I have wrote some extra printf()'s, which are actually for the programmer, so that he can see step-by-step if his code is acting as expected or not.
#include <stdio.h>
#include <stdlib.h> /* abs */
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
printf("|%d|", multi_array[i][c]);
}
printf("\n");
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i];
}
printf("sum1 is %d\n", sum1);
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i - 1];
}
printf("sum2 is %d\n", sum2);
printf("%i", abs(sum1 - sum2));
return 0;
}
Output:
3
11 2 4
4 5 6
10 8 -12
|11||2||4|
|4||5||6|
|10||8||-12|
sum1 is 4
sum2 is 19
15
You are clearly going out of bounds here:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
When i is equal to 0 the expression n-i will be equal to n, but the range of the array is from 0 to n-1. The code will read uninitialized values and cause undefined behavior.
The second array index should be 1 less.
I'm writing a program that reads integers from keyboard input and find the occurrence then sort them in descending order.
I got the occurrence and the descending but when I type same integers, they are repeated if I type 8 7 8
it's like
8 2
8 2
7 1
help please??
This is my code
#pragma warning (disable :4996)
#include <stdio.h>
#include <stdlib.h>
int main(){
int input;
int inputarr[50], count[50] = {0};
int i=0, j;
int last = 0;
printf("Enter numbers \n");
///getting int
while (scanf("%d", &input) > 0)
{
inputarr[i] = input;
i++;
}
last = i;
printf(" N Count\n");
printf("----- -----\n");
int a;
/// increment count
for (i = 0; i < last; i++){
count[inputarr[i]] = count[inputarr[i]] + 1;
}
/////ascending
for (i = 0; i < last; i++)
{
for (j = 0; j < last; j++){
if (inputarr[j]<inputarr[j + 1])
{
int temp = inputarr[j];
inputarr[j] = inputarr[j + 1];
inputarr[j + 1] = temp;
}
}
printf(" %d %d\n", inputarr[i], count[inputarr[i]]);
}
return 0;
}
The problem with this code is that you are printing the array while it's being sorted. Inputing numbers 1 2 3 4 would result in numbers 2 1 4 1 2 1 1 1 being outputed. To accomplish what you wanted you should move the printing part out of the sorting loop. Even then when a number is appearing multiple times in the input the output won't contain it only once (ex. 8 7 8 -> 8 2 8 2 7 2). To do that you should not output the number if it is the same as the previous number you outputed.
Another thing, in the sorting loop you are potentially accessing non existing array elements at the line
for (j = 0; j < last; j++){
When j = last-1 you are accessing last element which might not exsist.
After fixing all this problems code might look like this:
for (i = 0; i < last; i++)
{
for (j = 0; j < last-1; j++){
if (inputarr[j]<inputarr[j + 1])
{
int temp = inputarr[j];
inputarr[j] = inputarr[j + 1];
inputarr[j + 1] = temp;
}
}
}
if (last == 0)
return 0;
printf(" %d %d\n", inputarr[0], count[inputarr[0]]);
for(i = 1; i < last; i++)
if (inputarr[i] != inputarr[i-1])
printf(" %d %d\n", inputarr[i], count[inputarr[i]]);
Code1:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
putchar('\n');
}
return 0;
}
Output of Code1:
0 1 2 3
4 5 6 7
Remarks of Code1:
Space after 3 and 7
Newline after 7 (Stackoverflow has removed it)
Code2:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
{
printf("%hu", j);
if (j + 1 != k) putchar(' ');
}
if (i + 1 != 2) putchar('\n');
}
return 0;
}
Output of Code2:
0 1 2 3
4 5 6 7
Remarks of Code2:
No space after 3 and 7
No newline after 7
Additional remark of Code2:
The problem of Code2 is that the algorithm always compares two values in the if blocks and so Code2 is not efficient. I want to use Code1 and change these:
Code3
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
printf("\b\n");
}
putchar('\b');
return 0;
}
These do not show the same output of Code2 because \b does not erase anything.
My question:
Is there any standard way to do so what I've tried in Code3?
Remark of my question:
I have searched the internet but have not determined the solution.
Edit the question if it is not clear.
Edit: I don't know why my question is not useful or constructive. Though the above is an arbitrary small example, but performance might be an issue when processing very large amount of data. I thought that the way of removing character from console output might improve performance and there might be a specific way to do so. That's why I've asked the question. I could write the following codes in the answers. Now I've known via comments that removing character from console output is not possible because it is implementation dependent.
The usual approach to this is to treat either the first or the last printf as a special case (outside of the loop):
for(ii=0; ii<2; ii++) {
jj = 0;
printf("%d", jj); // first number printed without space.
for(jj=1; jj<4; jj++) {
printf(" %d", jj); // include the space before the number printed
}
if(ii<2-1) printf("\n");
}
Obviously I simplified how the loops are constructed and what is printed - for simplicity. You could make the first printf statement
printf("\n%d", jj);
then you have a newline at the start of your output (often a good thing) and then you don't need the if statement later - you just don't have a newline printed at the end of the line (because it will be printed at the start...)
There are marginally more efficient ways of doing this that would involve no if statements at all - but these all come at the expense of less readable code. For example, here is a "no loop unrolling and no additional if statements" version of the code:
http://codepad.org/01qPPtee
#include <stdio.h>
int main(void) {
int ii, jj;
ii = 0;
while(1) {
jj = 0;
while(1) {
printf("%d", jj); // include the space before the number printed
jj++;
if(jj<4) printf("."); else break;
}
ii++;
if(ii<2) printf("*\n"); else break;
}
return 0;
}
Output:
0.1.2.3*
0.1.2.3
Basically I have taken the functionality of the for loop and made it explicit; I also use a . rather than a and "*\n" rather than "\n" to show in the printout that things behave as expected.
It does what you asked without extra evaluation of the condition. Is it more readable? Not really...
If it really bothers you, you can unroll your loops a little so that you treat the last item as a special case:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 1; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu\n", j);
}
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu", j);
return 0;
}
#include <stdio.h>
int main(){
unsigned short num = 0, to=8;
while(num < to){
printf("%hu", num++);
if(num < to)
putchar(num % 4 == 0 ? '\n' : ' ');
}
#if 0
do{
printf("%hu", num++);
}while(num < to && putchar(num % 4 == 0 ? '\n' : ' '));
#endif
return 0 ;
}
Well, to try to answer your question, here's how I would do it:
for (i = k = 0; i < 2; i++){
if (i > 0) printf("\n");
for (j = 0; j < 4; j++, k++){
if (j > 0) printf(" ");
printf("%d", k);
}
}
I do it this way because I want to be sure every line but the first starts with a \n, and every item is separated by a space from the one before it.
Also, I do not want the row and column position to be intimately tied to the content of what is being printed.
In terms of performance, keep in mind that these if statements cost about 1 cycle, while each character printed costs at least hundreds if not thousands. printf goes through many layers of system calls to interpret its format string, build a buffer, send the buffer to the system I/O routines, which then cause repainting and scrolling of the console window. Get the idea?
DO NOT WORRY about performance unless you know you have a problem.
Then, don't guess. Use a diagnostic. Here's what I do.