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.
Related
int i,j,k;
int sayi=1;
for(i=1; i<=sayi; i+=2){
printf("%d",i);
printf("a");
printf("%d",i+2);
printf("a");
printf("%d",i+4);
printf("a");
printf("\n");
for(j=1; j<=sayi; j+=2)
printf("%d",i);
printf("a");
printf("%d",i+2);
printf("a");
printf("%d",i+4);
printf("\n");
for(k=1; k<=sayi; k+=2)
printf("%d",i);
printf("a");
printf("%d",i+2);
printf("a");
printf("\n");
printf("%d",i);
printf("a");
printf("%d",i+2);
printf("\n");
printf("%d",i);
printf("a");
printf("\n");
printf("%d",i);
}
I need to add the letter 'a' between the numbers as the numbers move in the form of 1-3-5 consecutively. I'm trying to get the output on the screen with nested for loops. But I think it's much shorter bit path than my method how can I do it?
You are already using nested for loops. Unfortunately, you aren't using them correctly.
for(j=1; j<=sayi; j+=2)
for(k=1; k<=sayi; k+=2)
These are both nested within the "for(i=1; i<=sayi; i+=2)" because of your brackets, { and }. These inner loops only have one line within them because you aren't using brackets to define where they start and end, so the compiler's rules automatically defaults to them consisting of only the one valid line of code following the loop.
None of the 3 loops you have in your example are actually running as loops because you aren't incrementing the "sayi" variable and it being 1. When you assign "i", "j", and "k" to 1 also, and compare that to "sayi" with a "less than or equal" comparison, they run because it's true, but then when you increment the loop variables by 2, they become 3 and the "less than or equal to" comparison fails, so the loop is only run once.
In order to shorten this, you'll need to learn quite a few things:
The if statement is a major piece of this. https://www.cprogramming.com/tutorial/c/lesson2.html
How loops actually work. https://www.freecodecamp.org/news/for-loops-in-c/
Mathematical, assignment, and conditional operators. https://www.programiz.com/c-programming/c-operators
The links I gave are just suggested starting points. There's more to learn than just that. I don't have any connection to those sites or people putting them out. They are simply the best of the first search results I looked at.
Here's my version of the code you are trying to write.
int start = 6;
for (int i = start; i > 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (j % 2 == 1)
{
printf("%d", j);
}
else
{
printf("a");
}
}
printf("\n");
}
To be certain, this can be reduced further, but I think this is a good enough starting point for you.
This should work. I put in some comments explaining it.
#include <stdio.h>
int main() {
//up to what number do you want it to go
int n = 5;
for (int i = n; i > 0; i--) { //loops over every line you need to print with i being the length of that line minus 1. I starts at n and ends at 0
for (int j = 1; j <= i; j++) { // loops over every number in that particular line, starting from 1 up to i.
if (j % 2) { //if j is even it prints 'a', otherwise it prints the number
printf("%d", j);
} else {
printf("a");
}
}
printf("\n");
}
}
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 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.
I've googled and read posts on stacks, but still don't know where my codes goes wrong on this problem set... it just keep asking typing "height". After typed height in, it doesn't go to next step, seems to stuck in an infinite loop.
Brain melting.
Please help to point out where my codes goes wrong. Thx a lot.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
printf ("height: ");
height = get_int();
}
while (height >= 0 || height <= 23);
for (int loop = 0; loop <= height; loop++)
{
for (int space = height - 1 - loop; space > 0; space--)
printf(" ");
for (int hash = 2 + loop; hash < height; hash++)
printf("#");
printf("\n");
}
}
Here, in the do while loop you are giving the condition that loop should continue whatever you put the height because every number is either >=0 or <=23.
Instead change the condition to while(height<0||height>23)
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++;
}