how to left align a set of characters in C - c

I am new to C and I have been trying to print a pyramid of * using for loops and printf() in a RIGHT ALIGNMENT manner; like this;
*
**
***
I can only do this
*
**
***

#include<stdio.h>
int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Here the first for-loop creates rows which are 5. Second for loop does the spacing and the third for loop prints the stars.
When
i = 1; j goes from 5 to 2 and prints spaces. After this k=1 and it prints one star.
i = 1; j = 5,4,3,2; k = 1
i = 2; j = 5,4,3 ; k = 1,2
.
.
i = 5; j = 0; k = 1,2,3,4,5
Here "-" represents a blank space.
So it goes down like this:
----*
---**
--***
-****
*****

You can use printf format specifier tricks mentioned in the comments or you can do this using basic for loops. Break down the problem step by step. First a loop for given number of lines, then a loop for spaces in each line, then a loop for stars in each line. Here's the code:
#include <stdio.h>
int main(){
int max_stars = 3;
// for every line
for(int i=1; i<=max_stars; ++i){
// print max_stars - i spaces
for(int j=1; j<= max_stars-i; ++j){
printf(" ");
}
// print i stars
for(int j=1; j<=i; ++j){
printf("*");
}
//print a new line
printf("\n");
}
return 0;
}

#include <stdio.h>
#include <string.h>
void f(int n)
{
int x = 1 , y , var ;
while( n > 0 )
{
for( var = n-1 ; var > 0 ; var-- )
{
fputc(' ',stdout);
}
for( y = 0 ; y < x ; y++ )
{
fputc('*',stdout);
}
fputc('\n',stdout);
n--;
x++;
}
}
int main(void)
{
f(3);
return 0;
}

Related

C program to create a square pattern with two triangles

So, the output should come out with a incrementing triangle of looped numbers (1,2,3,...) combined with a decrementing triangle of stars. Like this:
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
So far I have this but just can't figure out how to decrement the stars.
#include <stdio.h>
int main()
{
int i, j;
for(i=1; i<=9; i++)
{
for (j=1; j<=i; j++)
{
printf ("%d",j);
}
int k;
for(k=8; k>0; k--) {
printf("*");
}
printf("\n");
}
}
And it prints out this:
1*******
12*******
123*******
1234*******
12345*******
123456*******
1234567*******
12345678*******
123456789*******
You have:
For k in 8 down to 0 (exclusive),
Print *.
This always prints 8 stars, but you want 9-i of them.
For k in i+1 to 9 (inclusive),
Print *.
Note that all you need to do is subtract the amount of numbers printed per line from the expected (in this case) 9 expected characters. for(k=9 - i; k>0; k--)
#include <stdio.h>
int main()
{
int i, j;
for(i=1; i<=9; i++){
for (j=1; j<=i; j++){
printf ("%d",j);
}
int k;
for(k=9 - i; k>0; k--) {
printf("*");
}
printf("\n");
}
}
Outputs:
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
printf has the built in ability to print only limited portions of a string.
That comes in EXTREMELY handy for problems like this:
#include <stdio.h>
int main(void) {
int i=9;
while(i --> 0)
{
printf("%.*s%.*s\n", 9-i, "123456789", i, "********");
}
return 0;
}
Output
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
IDE Link
Begin with a mutable string of 9 stars. Then, replace one character at a time as you loop 9 times (ie: once for each row of output.)
#include <stdio.h>
int main( void ) {
char stars[] = "*********";
for( int i = 1; i <= 9; i++ ) {
stars[i] = (char)(i + '0');
puts( stars );
}
return 0;
}
You need 3 loops.
The outer most loop (i) keep track of line number
First inner loop (j) will print the digits in sequence equal to number of lines
Second Inner loop (k) will print *, such that number of * printed are total lines - line number i.e. (9-i)
https://godbolt.org/z/e65def4P5
#include <stdio.h>
int main()
{
for(int i=1; i<=9; i++)
{
for (int j=1; j<=i; j++)
{
printf ("%d",j);
}
for(int k=1; k<=9-i; k++) {
printf("*");
}
printf("\n");
}
}

Function prints infinitely when in loop, although it's not called repeatedly

I'm currently trying to solve a problem on Hackerrank where I have to print a pattern. Everything works as it's intended right now, except for the call of my loop function repeat_number inside the loop (!). It prints numbers infinitely, although it should only print it a fixed number of times.
This does not happen, when I call the function before the loop starts. When I print an integer variable it also prints only once. The error only occurs when I call repeat_number inside the loop.
Why is that?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void repeat_number(int number_to_repeat, int times_to_repeat) {
for (int e; e < times_to_repeat; e++) {
printf("%d ", number_to_repeat);
}
}
int main()
{
int n;
scanf("%d", &n);
// Complete the code to print the pattern.
// get number of rows
int rows = n * 2 - 1;
int starting_number = n;
// print row after row
for (int r; r < rows; r++) {
// count down
for (int i = rows; i > 0; i--) {
if (starting_number >= 1) {
printf("%d ", starting_number);
if (starting_number > 1) {
starting_number--;
}
else {
break;
}
}
}
// repeat number
repeat_number(5,1);
// test
//int test = 2;
//printf("%d", test);
// count up
for (int j = 1; j < rows; j++) {
if (starting_number >= 1) {
if (starting_number < n) {
starting_number++;
}
else {
break;
}
printf("%d ", starting_number);
}
}
printf("\n");
}
return 0;
}
This line looks very dangerous:
for (int e; e < times_to_repeat; e++)
I would replace it by:
for (int e = 0; e < times_to_repeat; e++)
Because: imagine that e get initialised as some very small number, then you can have an enormous loop: always initialise your variables!

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

Automatically filling an array

I want to define two variables called x and y.
Depending on that the program shall fill the array from 0 to x and from 0 to y.
I tried filling it with a for and it's kind of working, but I can't print it out properly.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
matrix[i][k] = k;
}
}
printf("\t\n%d\n", matrix[x][y]);
}
I expect an array looking like this in the console.
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
You see, in order to print an array you will have to loop over the whole data. You can't print an array in that simple a way in C.
What your code is printing is a garbage value, because at index 4,4 your array has no value. Its indexes go from 0,1..3 in both x and y direction.
Hope it helps.
#include <stdio.h>
#define x 4
#define y 4
void main(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i ;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
}
In C there is no way to print an array in one go. You have to loop through each element of the array and print it.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
I have tried to guess at your misunderstandings and commented and edited your code to make an explanation of how it works and what you need to understand.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y]; // top allowed indexes are x-1 and y-1
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i; // first write getting ignored/overridden by next
matrix[i][k] = k;
// printing here gets you many values, note the removed \n
printf("\t%d", matrix[i][k]);
}
// printing line break here gets you lines instead of single values
printf("\n");
}
// not inside any loop, so only one %d value gets printed
// printf("\t\n%d\n", matrix[x][y]); // accessing beyond both dimension
// also your attempt to let printf figure out how to print the whole 2D array,
// at least that is what I think you try, does not work in C
}

Queen puzzle 4x4

I am trying to solve this Queen problem of placing 4 queen in 4x4 matrix . I know it can be solved with backtracking algorithm . However i have not studied that and i am trying to solve it with my current knowledge . So what i am trying is to generate all possible combination of Queen in 4x4 matrix and print only one which cannot cancel each other .
1) For generating all combination , i am using rand function .
However there is obviously fault in my above coding . There are some outputs with only three '1' instead of four '1' . I am not able to eliminate this problem .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
int ar[30][30], i , j , a , b , c = -1, d = -1, k = 0;
while (1)
{
for (i = 0 ; i < 4 ; i++)
{
for (j = 0 ; j < 4 ; j++)
{
ar[i][j] = 0;
}
}
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (a != c || b != d)
{
ar[a][b] = 1 ; // here 1 = Queen
c = a ;
d = b;
}
}
}
}
}
2) Also is there any way i can reduce the time complexity using only these method ?
Instead of using temporary variables to check whether the array is filled, use the array itself!
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (ar[a][b] == 0)
{
ar[a][b] = 1 ; // here 1 = Queen
}
}
}
Your problem is that the inner loop will execute 4 times and you can only control 1 repeat with variables c and d.
Let's say a is 1 and b is 1: you make c = 1 and d = 1.
then a is 2 and b is 1 ... making c = 2 and d = 1.
then if a is 1 and b is 1 again, you cannot check for duplicate.
(1) You check only that a queen isn't placed on the same square as the last queen you placed. Remove the variables c and d and check whether ar[a][b] is still zero.
(2) Your scatter approach will produce many set-ups that are misses. Especially, because you don't enforce that ther cannot be any queens on the same rank and file. (In addition, rand() % 3 produces random values from 0 to 2, inclusively. You will never get a non-threatening configuration that way.)
If you want to use your random (bogosort) approach, you could use a one-dimensional array where the index is the rank and the number is the file where a queen is. Then you start with:
int queen[4] = {0, 1, 2, 3};
and shuffle the array. For 4 queens, that will yield 4! = 24 possibile configurations. You could try to iterate through them systematically.
The following is the brute force, backtracking code for the 8 queens problem, asked some time ago. Just change 8 to 4:
int checkBoard(int board[8][8]);
int putQueens(int board[8][8], int nQueens);
void printBoard(int board[8][8]);
int eightQueens(void)
{
int board[8][8];
memset(board, 0, sizeof(int)*64);
if (putQueens(board, 0)) {
printBoard(board);
return (1);
}
return(0);
}
int putQueens(int board[8][8], int nQueens)
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]==0) {
board[i][j]= 1;
if (checkBoard(board)) {
if (nQueens==7) return(1);
if (putQueens(board, nQueens+1)) return(1);
}
board[i][j]= 0;
}
}
}
return(0);
}
int checkBoard(int board[8][8])
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]) {
int ii, jj;
for (ii=i+1; ii<8; ii++) {
if (board[ii][j]) return(0);
}
for (jj=j+1; jj<8; jj++) {
if (board[i][jj]) return(0);
}
for (ii=i+1, jj=j+1; ii<8 && jj<8; ii++, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j-1; ii>0 && jj>0; ii--, jj--) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j+1; ii>0 && jj<8; ii--, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i+1, jj=j-1; ii<8 && jj>0; ii++, jj--) {
if (board[ii][jj]) return(0);
}
}
}
}
return (1);
}
void printBoard(int board[8][8])
{
int i,j;
printf(" ");
for (j=0; j<8; j++) printf(" %1d",j+1); printf("\n");
for (i=0; i<8; i++) {
printf("%1d ",i+1);
for (j=0; j<8; j++)
printf(" %1c", board[i][j]==0? '-':'*');
printf("\n");
}
}

Resources