So what I need to have as a finished product is a program that:
Asks for an int and only continues if the given is between one and eight. (Finished)
When given the number "8" a stairway that has eight hashtags in it's bottom row must appear. (Finished)
The stairway must be right-aligned, so there must be spaces printed to make the top right hashtag align with the bottom right hashtag. (Incomplete)
When the stairway is given the number "1" it must simply print a single hastag. (Incomplete)
My code is as follows:
int main (void)
{
int height = 0;
int change;
int row;
int space;
do{
height = get_int("Height: ");
} while(height < 1 || height > 8);
for (change = 0; change < height; change++ )
{
for (space = 7; space > change; space--)
{
printf(" ");
}
for (row = -1; row < change; row++)
{
printf("#");
}
printf("\n");
}
}
PLease can someone tell my which functions I need to implement so I can complete the final two criteria?
Change the starting value of space so it depends on the height, so you don't print more spaces than needed.
for (space = height-1; space > change; space--)
{
printf(" ");
}
Related
I've been sent a exercise where I have to print to the console (in C) a triangle using three different symbols in the following way:
The program must ask how many rows the triangle will have.
The program will print the triangle in the following way:
From outside to inside, the first triangle will be formed of *, the one inside it will be -, the one inside again will be $ and then the other way around...
This is my code:
#include <stdio.h>
int num = 0; //Var to store the user input.
int blank; //Var to store number of blank spaces.
int main() {
printf("Number of rows? ");
scanf("%d", &num);
printf("\n");
blank = num - 1;
//For loop to print each row of the triangle.
for(int k = 1; k <= num; k++) {
//For loop to print each blank space.
for(int j = 1; j <= blank; j++) {
printf(" ");
}
blank--; //Decrease number of blank spaces.
//For loop to print each symbol of the triangle.
for(int r = 1; r <= 2 * k - 1; r++) {
if(r % 2 == 0) {
printf("-");
}
else if(r % 3 == 0) {
printf("$");
}
else {
printf("*");
}
}
printf("\n");
}
blank = 1;
return 0;
}
And this is what it's printing:
Try working out the pattern on paper first.
For example, the dollar sign starts two rows below the top of the outermost triangle. All subsequent dollar signs are each one column before or one column after the preceding dollar sign. In this way each character of a new line is remotely dependent on the very first character.
Once you understand the underlying pattern, you can start programming the loop.
I am trying to print out an inverted hash triangle.
./upside_down_oddnumber
###########
#######
###
My work so far -
int main(void) {
int row, column;
int size;
printf("Enter size: ");
scanf("%d", &size);
row = 1;
while (row <= size) {
column = 1;
while (column <= size) {
if (row == (4 * size) -1 || row == column) {
printf("#");
} else {
printf(" ");
}
column++;
}
printf("\n");
row++;
}
return 0;
}
Currently it is printing a diagonal line sideways and I should use the equation 4n-1. How should I proceed from here? Any help will be greatly appreciated!!
Thanks :)
Start by examining the arithmetics behind the problem:
4*size-1 is the length of the top row of #, i.e. the width of your printout
Each row has an offset of spaces
The number of spaces starts at zero for the initial row, and increases by 2
These three observations should be enough to construct a program. Start row and column numbers at zero for consistency. Each row should be width characters long. Decide which character to print using this formula:
if (column >= offset && column < width-offset) {
printf("#");
} else {
printf(" ");
}
Demo.
The problem is your if statement.
The first section row == (4 * size) -1 is never going to be true, because the row will never be bigger then size, so 4*size will always be bigger then row and thus the statement will never give true.
The second section row == column will of course give you the line.
You should rethink your algorithm.
Or you could do
for(i=size; i>0; --i)
{
for(j=0; j<(4*size-1 - (4*i-1))/2; ++j)
{
printf(" ");
}
for(j=0; j<4*i-1; ++j)
{
printf("%c", '#');
}
printf("\n");
}
(4*size-1 - (4*i-1))/2 will give the number of spaces that must be printed at the start of each line.
After printing the required number of spaces, the #s are printed out.
You could also use
printf("%*s", (4*size-1 - (4*i-1))/2, "");
instead of the loop to print the spaces.
The * in %*s is used to specify the width of the string to be printed.
I want to display multiplication table which will look like this:
1 2 3 4 5 6 7 8
1 1x1=1
2 1x2=2 2x2=4
3 1x3=3 2x3=6 3x3=9
4 1x4=4 2x4=8 3x4=12 4x4=16
5 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
6 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
7 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
8 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
So far I have something like this:
#include <stdio.h>
int main()
{
int n, i;
scanf("%d", &n);
int row,col;
if(n<1 || n>9)
{
printf("input error");
return 0;
}
for (row=0; row<=n;row++){
if(row==0)
{
for(i=1; i<=n; i++)
{
printf("\t%d", i);
}
}
for(col=0; col<=row;col++)
{
if(col==0 && row>0)
printf("%d\t", row);
if(row>=1 && col!=0)
printf("%dx%d=%d\t", col, row, col*row);
}
if(row!=n)
printf("\n");
}
return 0;
}
I think it displays the table properly, but the code looks sloppy and I'm sure it can be done in a much cleaner way. Any suggestions?
I'd unroll the first pass through each of the loops that displays the row & column headers:
#include <stdio.h>
int main()
{
int n, i;
scanf("%d", &n);
int row,col;
if(n<1 || n>9)
{
printf("input error");
return 0;
}
for(i=1; i<=n; i++)
{
printf("\t%d", i);
}
printf ("\n");
for (row=1; row<=n;row++){
printf("%d\t", row);
for(col=1; col<=row;col++)
{
printf("%dx%d=%d\t", col, row, col*row);
}
if (row!=n)
printf("\n");
}
return 0;
}
Most of what makes your code look sloppy is simply bad style. Here are a few tips based on what is generally considered good style and best practice:
Print a prompt whenever your program is getting input from the user
Put all variable declarations together at the top of the main function
Use parenthesis to make the order of operations clear, especially when using the && and || operators
Make error messages clear
return a negative value to indicate an error
Put a space on both sides of binary operators (i.e. "n < 1" as opposed to "n<1")
Put a space after commas when declaring multiple variables
Put a space after semi-colons in for loop conditions
The following is generally considered a good-style for loop:
for (condition) {
...
}
The following is generally considered a good-style if statement
if (condition) {
...
}
Use comments to explain your code and increase readability
Use indentation to show code grouping
Aside from all of these things, your program also does not print a newline after the very last row (row n) due to the very final if statement. This causes the user's command-line prompt to be displayed on the same line as the last row printed by your program, which is probably not desirable.
Applying all of these things to your code gives the following result:
#include <stdio.h>
int main()
{
// all variables declared together, at the top of main
int n, i;
int row, col; // space after comma
printf("Enter multiplication table size: "); // prompt
scanf("%d", &n);
// better-style if statement
if ((n < 1) || (n > 9)) { // parenthesis make the order of operations clearer
// clearer error message, with a newline at the end
printf("Error: table size must be at least 1 and not greater than 9\n");
return -1; // return a negative value to indicate an error
}
// better-style for loop
for (row = 0; row <= n; row++) { // spaces around binary operators, space after semi-colons
// better-style if, indented also
if (row == 0) {
// better-style for, indented
for (i = 1; i <= n; i++) { // spacing
printf("\t%d", i); // indented
}
}
// better-style for
for (col = 0; col <= row; col++) { // spacing, indentation
if ((col == 0) && (row>0)) // parenthesis, spacing, indentation
printf("%d\t", row); // indentation
if ((row >= 1) && (col != 0)) // parenthesis, spacing, indentation
printf("%dx%d=%d\t", col, row, col * row); // indentation, spacing
}
// surrounding if statement removed, so a newline is printed after every row, including the last one
printf("\n");
}
return 0;
}
Note that I mainly used comments to explain the changes I made to your code, whereas you would want to use them to explain the functionality.
input
6 6 4
output
######
#....#
#....#
#....#
#....#
######
input
7 7 4
output
#######
#.....#
#.....#
#.....#
#.....#
#.....#
#######
This is the code I have so far.
#include <stdio.h>
int main()
{
int width;
int breadth;
scanf("%d", &width);
scanf("%d", &breadth);
if (width == 1 && breadth == 1)
{printf ("#\n");}
else{
for(int i = 0; i<breadth; i++){
for(int j = 0; j<width;j++)
{
{printf("#");}
}
printf("\n");}
}
return 0;}
Does anyone know how to replace the non boundary area with "."?
ps:there is no need to worry about the third input, it does not affect the shape of rectangles since its just going to be used next task.
I am guessing that I could perhaps change my for loops but I ran out of ideas at this point.
It would be greatly appreciated if someone could help me return identical output from above.
Thank you.
You want to replace non-boundary area with ".". To achieve that you need a condition that satisfies your boundary.
#include <stdio.h>
int main()
{
int width;
int breadth;
scanf("%d", &width);
scanf("%d", &breadth);
if (width == 1 && breadth == 1)
{printf ("#\n");}
else{
for(int i = 0; i<breadth; i++){
for(int j = 0; j<width;j++)
{
if(i==0||j==0)
printf("#");
else if(i==(breadth-1)||j==(width-1))
printf("#");
else
printf(".");
}
printf("\n");}
}
return 0;
}
Hope this works. Let me know if it does not or any problem is there.
Here is the working code.
You were almost there. You need the condition statement to check the boundary..
Please see the line that checks the boundary
#include <stdio.h>
int main()
{
int width;
int breadth;
scanf("%d %d", &width, &breadth);
if (width == 1 && breadth == 1)
printf ("#\n");
else
{
for(int i = 0; i<breadth; i++)
{
for(int j = 0; j<width;j++)
//Check for boundary.
if( j == 0 || j == width - 1 || i == 0 || i == breadth - 1 )
printf("#");
else
printf(".");
printf("\n");
}
}
return 0;
}
You should use counters. For example, one counter should be refering to which line you're printing and another one the column you're printing on.
If the line counter is 0, print all the line as '#' cause it's going to be the upper boundary line
(this creates -> #######)
Else If the line counter is same as the height of the shape, then it's the finishing border line
(#######)
Else if it's >0, print the first character as '#', then print '.' until another counter reaches the width of the shape -1 (for example in 7 7 that would be 5 (since 0 also counts)) and then another '#'
(#.....#)
I think this is enough help for you to get it done by yourself, should you require further assistance tho, just ask.
I have check it by gcc ,it works.Please see the notes in code:
int main()
{
int width;
int breadth;
scanf("%d",&width);
scanf("%d",&breadth);
for(int i = 0; i < width; i++){
for(int j = 0; j < breadth; j++ ){
//first line and last line
if((i == 0)||i == (width - 1)){
printf("#");
//first column and last column
}else if((j == 0)||(j == (breadth -1))){
printf("#");
//other case
}else{
printf(".");
}
}
printf("\n");
}
return 0;
}
Using conditions as suggested by other answers is the ideal way but if that is unclear, you can break down the printing into smaller loops as
for (i=0; i<width; i++) // prints the first line
printf("#"); //
printf("\n"); //
for (j=0; j<breadth-2; j++){ // prints middle breadth-2 lines
printf("#"); // prints the starting hash in middle lines
for (i=0; i<width-2; i++) // prints the '.'s
printf(".");
printf("#\n"); // prints the last hash in middle lines
}
for (i=0; i<width; i++) // prints the last line
printf("#"); //
printf("\n"); //
Although not very efficient, the logic is very easy to understand.
Let me know if further explanation is required.
Edit: Actually after writing this answer I later realized that this code will infact be faster than the ones with branches. Since we have split the iteration domains ourselves, there are no branches. This reduces any chance of branch prediction failing, which would certainly happen in the solution with if conditions since the condition is true for small cases. Ofcourse it wouldn't matter for small iterations like 6x6, but just putting the thought out there.
I've been given an assignment question, and I've managed to figure it all out so far, with the exception of splitting a remainder value betwen a few (input determinate) characters.
Any help would be greatly appreciated.
For reference, my assignment question is:
"If you look at a newspaper you will see that the writing is justified to fit into the columns. Write a program that reads in the width of the columns in a newspaper and then a line of text. Justify the line of text to fit into a column of that width. When your program is running, the screen should look something like this:
Enter the width of the column: 40
Enter a line of text: Good morning how are you?
12345678901234567890123456789012345678901234567890...
Good morning how are you?
The justification is done by counting the number of gaps in the text. In the above example, there are 4 gaps. Then each gap must have spaces added to it. The number of extra spaces must be shared out as evenly as possible. In the above example, the first three gaps have 5 spaces each and the last gap has 4 spaces.
Notes:
If the text is longer than the column then you must report an error – don't try and break it into two lines!
Assume that the text will have more than one word in it.
Note the header line consisting of 123456789012345678.... this is useful to check your result.
You can make this header line as long as you like – 70 spaces would be a useful length.
"
And my code so far is:
int main() {
//input column width
printf("Enter the width of the column: ");
int column;
scanf("%d", &column);
//input text line
printf("Enter a line of text: ");
char string[80];
getchar();
gets(string);
//print 1234567890 column header
int y = 1,x = 0;
while(x < column){
if(y > 9){
y = 0;
}
printf("%d", y);
y++;
x++;
}
printf("\n");
//count spaces
int i = 0;
int space_count = 0;
while(string[i] != '\0'){
if(string[i] == 0x20){
space_count++;
}
//printf("%c", string[i]);
i++;
}
//work out variables
int string_length = i;
int remainder_space = (column - string_length);
int space_power = (remainder_space / space_count);
//int oddremainder = (space_count % remainder_space) ;
//space_power = (space_power + oddremainder);
//if
//remainder %
//insert column width check
if(string_length > column)
{
printf("Text is too long. Shouldn't be more than %dcharacters\n",
column);
return 1;
}
//output
i = 0;
while(string[i] != '\0'){
if(string[i] == 0x20){
for(x = 0; x < space_power; x++){
printf("%c", 0x20);
}
}
printf("%c", string[i]);
i++;
}
I'm sorry if this isn't the appropriate way of asking a question, my brain is fried and I can't get my head around this.
Any pointers or discusion in the right direction would be greatly appreciated.
Lets see the example. It has 19 spaces to be filled in 4 gaps. If your code runs like that, the value of space_power will be 4 (int(19/4)), and this leaves 3 spaces in the end. You need to keep track of 19 % 4, ie. 3 extra spaces.
So, keep a count, initially equal to 3. Then, while this count is greater than 0, print one extra space along with all space_power number of spaces. Decrease count every time you print a word.
Your code would be like this:
count = remainder_space % space_count;
and output block:
i = 0;
while(string[i] != '\0'){
int k = count > 0 ? 1 : 0;
if(string[i] == 0x20){
for(x = 0; x < space_power + k; x++){
printf("%c", 0x20);
}
count--;
}
printf("%c", string[i]);
i++;
}