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.
Related
I have written a program that should be rather simple but on execution, it is not giving the wanted results. Even when debugging the program, I guess I found the error (getting stuck in the first if condition) but I'm not able to solve it (my inexperience perhaps). Anyways, this program, which should have been frugal, took 3 days whereas I expected it to take mere hours. Please help me with guiding me where I'm going wrong and how to solve it.
Here is the code
/*WAP to read pre entered no. of ints. consider only +ve and print the pythagorean triplets in them.*/
#include <stdio.h>
int main(){
int c,p,pp,count=0,a;
printf("How many entries to accept?\n");
scanf("%d",&a);
printf("Enter the nos.\n");
for (int i = 0; i < a; i++)
{
scanf("%d",&c);
if (c<0) //skip -ve nos.
{
continue;
}
if (count==0)
{
pp=c;
count++;
}
else if (count==1)
{
p=c;
count++;
}
else if ((pp*pp)+(p*p)==(c*c)) //Tracking count not necesarry after first three
{
printf("Pythagorean triplet found\n");
printf("%d %d %d",pp,p,c);
pp=p;
p=c;
}
}
return 0;
}
The main objective is to first scan a no. to signify the inputs to be read. Then scan the inputs, separated by a space or enter, in a loop which will only accept the no. of inputs stated before. It should neglect any -ve entries. It should print out the Pythagorean triplet if it encounters one, in a consecutive manner i.e. the triplet should appear one after the other & not randomly. We have to do the task without using arrays.
sample input is (you can consider any)(all given through the terminal)
(no. of entries)
6
1 -1 3 4 -4 5
(Here it will ignore -1 & -4)
expected output will be
Pythagorean triplet found
3 4 5
I am still learning so sorry for the elaborate program.
Thank you in advance.
since I cant see the input file I dont know if the values are sorted, since we need to identify which is the hypotenuse, makes it a bit more fiddly.
Also not clear what 'skip negatives' means. Does it mean
that we might see 3 -6 4 5 and say 'yes 3,4,5' is a triple
that we might see 3 -4 5 and say yes 3 4 5
or that we might see 3 -4 5 and simply ignore the whole set
I have assumed the first one
#include <stdio.h>
int main() {
printf("How many entries to accept?\n");
int a;
if (scanf("%d", &a) != 1) {
printf("bad input\n");
return (-1);
}
printf("Enter the nos.\n");
for (int i = 0; i < a; i++)
{
int sides[3] = { 0 };
int max = 0; // longest side length -> hypot
for (int j = 0; j < 3; j++)
{
int c;
if (scanf("%d", &c) != 1) {
printf("bad input\n");
return (-1);
}
if (c < 0) //skip -ve nos.
j--; // try again
else {
if (c > max) {
max = c;
}
sides[j] = c;
}
}
int hyp = max * max; // hypotenuse squared
int adjTot = 0; // adj sides squared total
for (int j = 0; j < 3; j++)
{
if (sides[j] == max)
continue;
adjTot += sides[j] * sides[j];
}
if (adjTot == hyp)
printf("%d %d %d is py\n", sides[0], sides[1], sides[2]);
else
printf("%d %d %d isnt py\n", sides[0], sides[1], sides[2]);
}
return 0;
}
Since you say you are reading from a file it just exits if there is non numeric data
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(" ");
}
I am trying to find the closest pair of numbers entered by the user. My C code isn't working right and I can't figure out what's wrong. I think it might have something to do with storing the values but I don't know where to go from here.
#include <stdio.h>
#include <math.h>
int main()
{
int i, j,arr[50], first,second;
//loop input
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
//2nd num - 1st num < 3rd num-1st num, closest = 1st and 2nd num
//i[0]=num1, j[0+i]=2nd num, i= 4 , 5, 7, ans=arr,
//if j[0+i]-i[0]= ans < j[0+i]-i[i]=ans
//arr[i]=8,2,17,4,25
for(i=0;i<50;i++)
{
for(j=i+1;j<50;j++)
{
if(arr[j]-arr[i]<arr[j+1]-arr[i])
{
first = arr[i];//3
second = arr[j+1];//5
}
}
}
printf("%d %d\n", first, second);
return 0;
}
Don't post it as answer, prefer editing your code instead. Anyway, the problem is here :
for (j = i + 1; j < len; j++)//j<i <-why is it wrong?
How isn't it wrong? You've initialised j with the value i+1. How's it supposed to be ever less than i? And due to that, it's picking up values from outside the array and providing you with unexpected results.
The correct form is :
for (j = 0; j < i; j++)
The problem is with this chunk of code. You're scanning in the counter variable i instead of array. And then you're manipulating stuff using array arr. Why should that work in any scenario?
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
And i can never be -1 unless it's a miracle.
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++;
}