C program to create a square pattern with two triangles - c

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

Related

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
}

Return string instead of int

When I print out a pyramid, the last line of the pyramid or the base prints out an integer which represents how many hashes, instead of a string of hashes.
like such:
Height: 3
#
##
3
when its supposed to be:
Height 3:
#
##
###
I'm supposed to print out a pyramid with a height based on the user's input, but instead of the base being printed out as a string it prints out an integer of how many hashes there should be for the base. I understand that this is because I'm returning n but I don't know how to go about it in a way where it still returns the loop.
I've tried changing the class to void instead of int, but that throws an error as it's conflicting types. I'm thinking I should print out an empty string but it messes with my bounds.
#include <cs50.h>
#include <stdio.h>
int get_height(string prompt);
int main(void)
{
int ask = get_height("Height: ");
printf("%i\n", ask);
}
int get_height(string prompt) {
int n;
do {
n = get_int("%s", prompt);
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
printf("#");
}
printf("\n");
}
return n;
}
The last line of output is the height because that is the last thing printed in your main function:
printf("%i\n", ask);
get_height will actually only print n-1 lines because the first iteration (i=0,j=0) is skipped.
the 3 should be output
The problem is this statement;
for (int j = 0; j < i; j++) {
which stops too early. Suggest:
for (int j = i; j >=0; j--) {
The output after making the above change:
#
##
###
3

Possible mistake in bubble sort c program

I was reading the book "Computer Organization and Design" by Patterson and Hennesy (5th Edition) and found this bubble sort code:
void sort (int v[], int n)
{
int i,j;
for (i=0; i<n; i+=1) {
for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
swap(v,j);
}
}
}
void swap (int v[], int k) {
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
I don't understand how this function would sort an array. Especially if the first element of the array is also the largest, it seems to me that the index j would go out of bounds. Running the code and printing the indices confirmed this.
This is the code I used:
#include <stdio.h>
void swap (int v[], int k) {
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
void sort (int v[], int n)
{
int i,j;
for (i=0; i<n; i+=1) {
printf("%d \n", i);
for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
printf("%d, %d \n", i, j);
swap(v,j);
}
}
}
int main() {
int x[3] = {5,1,2};
int N = 3;
sort(x, N);
for(int i = 0; i < 3; i++) {
printf("%d ", x[i]);
}
return 0;
}
This was the result:
/Users/mauritsdescamps/Desktop/test/cmake-build-debug/test
0
1
1, 0
1, 1
1, 2
1, 3
1, 4
2
2, 1
2, 2
2, 3
Process finished with exit code 6
Is there something I am forgetting? If not, I think there must be a mistake in the second loop condition. I have seen other implementations of the algorithm but I want to know how to get this approach to work.
I've tried this code, too. I have compiled it with GCC and somehow it worked for me (the exit status of the program was 0 and the array was sorted correctly). But I also think that their is a problem with the second loop. I would change the j+= 1 instruction into j-=1. Otherwise the second loop could end in an infinite loop. Additionally I would change the i=0 instruction in the first loop into a i=1 instruction, because it would end in an unnecessary iteration.

Nested for loops in C language

An abundant number is a natural number that is less than the sum of its proper divisors. For example 12 < 1+2+3+4+6=16 so 12 is an abundant number, while 16 > 1+2+4+8=15 is not an abundant number.
I have to write a program in C language so that for the input k, the output are all abundant numbers less than or equal to k.
I'm only a beginner at this so what I first wanted to do is to write a program that will check whether k is abundant or not. So this is what I did:
#include <stdio.h>
int main(void) {
int k, i, s = 0;
scanf("%d", &k);
for (i = 1; i < k; i++) {
if (k % i == 0)
s = s + i;
}
if (k < s)
printf("%d" is an abundant number", k);
return 0;
}
Feel free to ignore this above, I only wanted to show you I actually tried something by myself. Now I wasn't sure how to make this program list the abundant numbers that are also less than k, but I found the solution which I don't understand:
#include <stdio.h>
int main(void) {
int k, i, j, s;
scanf("%d", &k);
for (i = 1; i <= k; i++) {
s = 0;
for (j = 1; j < i; j++) {
if (i % j == 0)
s = s + j:
}
if (i < s)
printf("%d"\n", i);
}
return 0;
}
I'm confused by this nested for loop, can someone explain exactly how it works? For instance if we put k=18, what exactly happens with this for loops so that in the end we get 12 and 18 as output?
I think the best way is to step through the code manually and write down the line number of the executing code and how the variables change.
Like
L01: int k,i,j,s; // k=?, i=?, j=?, s=?
L02: scanf("%d", &k); // k=18, i=?, j=?, s=?
L03: for(i=1; // k=18, i=1, j=?, s=?
L03: i<=k; // TRUE
L04: s=0; // k=18, i=1, j=?, s=0
L05: for(j=1; // k=18, i=1, j=1, s=0
L05: j<i; // FALSE
L03: i++) // k=18, i=2, j=1, s=0
L03: i<=k; // TRUE
L04: s=0; // k=18, i=2, j=1, s=0
L05: for(j=1; // k=18, i=2, j=1, s=0
L05: j<i; // TRUE
L06: if(i%j==0) // TRUE
L07: s=s+j: // k=18, i=2, j=1, s=1
L05: j++) // k=18, i=2, j=2, s=0
L05: j<i; // FALSE
and so on ....
I takes quite some time but you should soon see the pattern and there by understand how for-loops works.
Another thing that might help you understanding for-loops are to realize that
for(i=0; i<N; i++)
{
code...
}
is equivalent to
i=0;
while (i<N)
{
code...
i++;
}
BTW:
Always check the return value from scanf - like:
if (scanf("%d", &k) != 1)
{
printf("Input error! Program terminates.\n");
exit(1);
}
the inner loop is executed k time;
when i=1 nothing happens
when i=2 the inner loop checks if 2 is abundant or not
when i=3 the inner loop checks if 3 is abundant or not
and so on. Maybe it would be better to rewrite your code so that variable names explains its meaning.
I have written a simpler implementation. This is same as your own attempt. just that it is enough to run till k/2 instead of k-1
#include<stdio.h>
int main(void) {
int k,i,j,s;
scanf("%d", &k);
s=0;
for(i=1; i<=(k/2); i++) { //running till half of the entered value is sufficient
if(k%i == 0)
{
s+=i; //if it is a divisor add it to the sum
}
}
printf("sum is %d\n\r",s);
if(k<s)
printf("%d is abundant\n\r",k);
else
printf("%d is not abundant\n\r",k);
return 0;
}
#include<stdio.h>
int main(void) {
int upper_limit,candidate,divisor,s;
scanf("%d", &upper_limit);
for(candidate=1; candidate<=upper_limit; candidate++) {
s=0;
for(divisor=1; divisor<=(candidate/2); divisor++) {
if((candidate%divisor)==0)
s=s+divisor:
}
if(candidate<s)
printf("%d"\n", candidate);
}
return 0;
}

how to left align a set of characters in 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;
}

Resources