I have been stumped by this problem. I need to create a pattern such as:
1
21
221
2221
22221
Using nested for loops. I have something that does (A)
222221
222221
222221
222221
222221
and used to have something that did (B)
/* 1
* 21
* 221
* 2221
* 22221
* 222221
* 2222222
*/
#include <stdio.h>
main()
{
int n, c, k;
printf("Enter number of rows\n");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++ )
{
printf("1\n");
for( k = 1 ; k <= c ; k++ )
printf("2");
}
return 0;
}
Any hints would be helpful.
Solution - Thanks to the intelligent people that decided to help.
I appreciate your help!
#include <stdio.h>
main()
{
int n, c, k;
printf("Enter number of rows");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++ )
{
for( k = 1 ; k < c ; k++ )
{
printf("2");
}
printf("1\n");
}
return 0;
}
This can be done using nested for loops. Let's examine the formulae for one line of the output:
line 1:
1
Which can be made using a simple for loop like this:
for (int i = 0; i < 1; i++)
{
putc('1', stdout);
putc('\n', stdout);
}
line 2:
21
Hmm, this requires change to our structure, as we can't break the output of iteration #1, but we still need to be able to add the '2' in there... Something like this should work:
for (int i = 0; i < 2; i++)
{
if (i > 0)
putc('2', stdout);
putc('1', stdout);
putc('\n', stdout);
}
line 3:
221
Wait, now we need two '2's in there! How can we do this without breaking line's 2 and three? Well something like this should do it:
for (int i = 0; i < 3; i++)
{
int j = i;
while (j--)
{
putc('2', stdout);
}
putc('1', stdout);
putc('\n', stdout);
}
Notice that I used a while loop instead of a for loop. It is an exercise to the reader to figure out how to turn that while loop into a for loop.
Hopefully this helped you to understand the process behind solving similar problems like this in the future - as it is an important programming skill to have.
Here is some code that generates your first pattern.
#include <stdio.h>
#define NUMLINES 5
int main(void) {
int i, j;
for(i=0; i<NUMLINES; i++) {
for(j=0; j<i; j++) {
printf("2");
}
printf("1\n");
}
return 0;
}
The important part is that the inner for loops until the current value of the outer loop is reached (j<i).
Related
My code is supposed to make a pyramid as such, but just gives me a line, why? I've tried changing the conditions of the for and while loops and haven't found any solution. Any help would be appreciated!!
#
##
###
####
#####
######
#######
########
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Add the height of the pyramid: ");
int j = 0;
for(int i = 0; i < n ; i++) {
while (j <= i) {
printf("#");
j = j + 1;
}
printf("\n");
}
Declare j inside the for loop so it starts at 0 on each iteration.
for(int i = 0; i < n; i++) {
int j = 0;
while (j <= i) {
printf("#");
j = j + 1;
}
printf("\n");
}
The inner loop could also be rewritten as a for loop.
for(int i = 0; i < n; i++) {
for (int j = i; j >= 0; j--) printf("#");
printf("\n");
}
While the answer from #Unmitigated is correct, this would be a great place to break out some functionality into a function.
void print_n_ln(char *str, int n) {
for (; n > 0; n--) {
printf("%s", str);
}
printf("\n");
}
Then:
int main(void) {
int n = get_int("Add the height of the pyramid: ");
for (int i = 1; i <= n; i++)
print_n_ln("#", i);
return 0;
}
While an iterative solution (nested for() loops) would be simplest, this might be a good time to discover recursion. As long as the pyramid is not so tall as to risk stack overflow, the following works (leaving gathering/validating user input as an exercise.)
#include <stdio.h>
#include <cs50.h>
void print( int n ) {
if( n > 1 )
print( n - 1 );
while( n-- )
putchar( '#' );
putchar( '\n' );
}
int main() {
print( 7 );
return 0;
}
putchar() is a much simpler function than printf() and should be used when outputting a simple single character (for speed and efficiency.)
If you think your way through the operation presented, you will come to understand recursion and how it may sometimes be used to solve problems.
Another (albeit 'limited') solution follows:
int main() {
char wrk[] = "################";
int i = sizeof wrk - 1; // 'i' starts as the 'length' of the string
int want = 7;
while( want-- )
puts( wrk + --i ); // adding decreasing values of 'i' prints longer strings
return 0;
}
puts() will output a string to stdout while appending a 'newline'.
NB: Its more general sibling function (fputs()) works in a similar fashion, but does NOT append the LF for you.
There are often many ways to do things.
EDIT:
Here's another minimalist solution using pointers. This one uses a "compile time" string, so is not easily amenable to influence by a user (but it could be made so, if you're clever.)
#include <stdio.h>
#include <string.h>
int main() {
char want[] = "#######";
char *p = want + strlen( want );
while( --p >= want) puts( p );
return 0;
}
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;
}
I wanted to print a rhombus shape with only 1 loop. The furthest I have gone is using 2 for loops.
The result shape is as follows:
rhombus shape
*
* *
* *
* *
* *
* *
* *
* *
*
The code for using 3 loops is as follows:
#include <iostream>
int main() {
int i, j;
int columns = 4;
for(i = 0; i < columns; i++){
for(j = 0; j <= (columns-1) - i;j++){
printf(" ");
}
for(j = 0;j<=2*i;j++){
if(i == 0||j == 0||j == 2*i){
printf("*");
}else{
printf(" ");
}
}
printf("\n");
}
for(i = columns; i >= 0; i--){
for(j = 0; j <= (columns-1) - i;j++){
printf(" ");
}
for(j = 0;j<=2*i;j++){
if(i == 0||j == 0||j == 2*i){
printf("*");
}else{
printf(" ");
}
}
printf("\n");
}
}
My code is as follows:
int main() {
int i, j;
int columns = 4;
for(i = 0; i < columns; i++){
for(j = 0;j<=(2*i+(columns) - i);j++){
if(j==columns/2+(columns/2-i)||(j == (2*i+(columns) - i))){
printf("*");
}else{
printf(" ");
}
}
printf("\n");
}
for(i = columns; i >=0; i--){
for(j = 0;j<=(2*i+(columns) - i);j++){
if(j==columns/2+(columns/2-i)||(j == (2*i+(columns) - i))){
printf("*");
}else{
printf(" ");
}
}
printf("\n");
}
}
I have the following questions:
Does less loop in rhombus shape printing always faster than using more loops?
Is there a way to print rhombus shape using 1 loop? Without using predefined functions like string().
Sorry for my English, looking forward to hearing from you guys.
Let's address the questions in order...
Does less loop in rhombus shape printing always faster than using more loops?
Firstly, you should not be concerned about speed in a program like this. Except maybe if you are trying to print a HUGE rhombus or this is intended to run on a small battery-operated embedded device requiring low power consumption.
I don't think you're doing any of these.
The answer really is no: both your approaches are doing roughly the same amount of looping. They're not very efficient, because they are calling a fairly expensive function once for each character output.
More importantly, the code is overly complicated, unclear and difficult to read. You should be focusing here, instead of worrying about trivial performance considerations.
Is there a way to print rhombus shape using 1 loop? Without using predefined functions like string().
Yes, I posted an example in the comments where you can just use a specifier in the printf call to output some amount of padding. Internally, that does basically the same thing as your own loops, but it makes shorter, clearer code and fewer printf calls.
Here, you just work out how many spaces are required before the * and then how many after it. You can then ask printf to output the string "*" padded with some number of spaces. Use %*s to indicate there are two parameters: the total width of the string, and the string itself. The width will be the number of spaces you want, plus 1 for the actual string.
#include <stdio.h>
#include <math.h>
int main(void)
{
const int N = 4;
for (int i = 0; i <= N*2; i++)
{
int space_before = abs(N - i);
int space_after = 2 * (N - space_before ) - 1;
if (space_after > 0)
printf("%*s%*s\n", space_before + 1, "*", space_after + 1, "*");
else
printf("%*s\n", space_before + 1, "*");
}
return 0;
}
Now, this is easier to understand, but it's still a bit clunky. How about we move it into a function, and then get rid of the branching in the loop. All the loop iterations output two stars except the first and last ones which are simpler. So, here:
#include <stdio.h>
#include <math.h>
void display_rhombus(int size)
{
if (size > 0)
{
printf("%*s\n", size + 1, "*");
for (int i = 1; i < size*2; i++)
{
int space_before = abs(size - i);
int space_after = 2 * (size - space_before ) - 1;
printf("%*s%*s\n", space_before + 1, "*", space_after + 1, "*");
}
}
printf("%*s\n", size + 1, "*");
}
int main(void)
{
display_rhombus(4);
return 0;
}
Now, you have a function with a name that describes what it does, has simple-to-understand code, and is re-usable. You can call it many times to draw whatever sizes of rhombus you want.
int main(void)
{
for (int size = 0; size < 10; size++)
{
display_rhombus(size);
}
return 0;
}
Finally, I should also mention that it's possible to output a rhombus with no loops, using a technique called recursion. I will leave that as a learning exercise for you.
Well, apart from paddy's excellent answer, here's another one:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
void printStar(int size) {
int j = size / 2;
int i = size % 2 == 0 ? j - 1 : j;
bool flag = false;
while (i <= j) {
std::vector<char> vec(size, ' ');
vec.at(i) = '*';
vec.at(j) = '*';
std::copy(vec.begin(), vec.end(), std::ostream_iterator<char> {std::cout});
std::cout << "\n";
if (!flag) {
i--;
j++;
}
else {
i++;
j--;
}
if (i == -1) {
flag = true;
i += 2;
j -= 2;
}
}
}
int main() {
printStar(5);
return 0;
}
I have an array with 100 numbers in it, and I am trying to print it out with only 10 ints on each line, and a tab between each number. It is only printing the first 10 integers and then stopping, which makes sense because of my for loop. I am clearly missing part of it to allow for it to continue through the array. I was going to try to add the line
for(int line_num = 0; line_num < 10; line_num+=10)
before the for statement after the while loop
int array_value;
int length_of_array = 100;
while (length_of_array <= 100){
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
I was also thinking of including a line like
if (array_value % 10 == 0)
printf("\n");
I figured it out! Posted the answer below.
This might be what you're looking for:
/* test.c */
#include <stdio.h>
#define ELEMENTS 100
int main (void)
{
int array [ELEMENTS];
for ( int i = 0; i < ELEMENTS; ++i )
array [i] = i;
for ( int i = 0; i < ELEMENTS; ++i ) {
printf ("%i", array[i]);
if ( (i + 1) % 10 != 0 )
printf ("\t");
else
printf ("\n");
}
return 0;
}
edit: Because of the way the tab can extend to the next line at the end of the line you have to be careful with the tab and new line character.
For clarity, rename length_of_array to offset_in_array and then set it to zero at the start. I renamed array_value and corrected your length check. I also added a check to the inner loop in case the array length gets changed and doesn't divide by 10.
Something like:
int i;
#define ARRAY_LENGTH 100
int offset_in_array = 0;
while (offset_in_array < ARRAY_LENGTH){
for(i = 0; i < 10 && offset_in_array < ARRAY_LENGTH; ++i){
printf("%d ", A[offset_in_array]);
++offset_in_array;
}
}
I haven't tried running this but it should be closer.
Just print a newline every tenth number... If it's not a tenth number, then print a tab.
for (size_t i = 0; i < array_length; ++i) {
printf("%d%c", A[i], i % 10 != 9 ? '\t' : '\n');
}
Live code available at onlinedbg.
Just change the value of length_of_array to 0 and print \n after a for loop.
int array_value;
int length_of_array = 0;
while (length_of_array <= 100) {
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
printf("\n");
}
You can use the following solution to print 10 lines of 100 array values in C:
for (int i = 0; i < 100; ++i){
printf("%i\t", A[i]);
if ((i+1)%10 == 0){
printf("\n");
}
}
Code1:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
putchar('\n');
}
return 0;
}
Output of Code1:
0 1 2 3
4 5 6 7
Remarks of Code1:
Space after 3 and 7
Newline after 7 (Stackoverflow has removed it)
Code2:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
{
printf("%hu", j);
if (j + 1 != k) putchar(' ');
}
if (i + 1 != 2) putchar('\n');
}
return 0;
}
Output of Code2:
0 1 2 3
4 5 6 7
Remarks of Code2:
No space after 3 and 7
No newline after 7
Additional remark of Code2:
The problem of Code2 is that the algorithm always compares two values in the if blocks and so Code2 is not efficient. I want to use Code1 and change these:
Code3
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
printf("\b\n");
}
putchar('\b');
return 0;
}
These do not show the same output of Code2 because \b does not erase anything.
My question:
Is there any standard way to do so what I've tried in Code3?
Remark of my question:
I have searched the internet but have not determined the solution.
Edit the question if it is not clear.
Edit: I don't know why my question is not useful or constructive. Though the above is an arbitrary small example, but performance might be an issue when processing very large amount of data. I thought that the way of removing character from console output might improve performance and there might be a specific way to do so. That's why I've asked the question. I could write the following codes in the answers. Now I've known via comments that removing character from console output is not possible because it is implementation dependent.
The usual approach to this is to treat either the first or the last printf as a special case (outside of the loop):
for(ii=0; ii<2; ii++) {
jj = 0;
printf("%d", jj); // first number printed without space.
for(jj=1; jj<4; jj++) {
printf(" %d", jj); // include the space before the number printed
}
if(ii<2-1) printf("\n");
}
Obviously I simplified how the loops are constructed and what is printed - for simplicity. You could make the first printf statement
printf("\n%d", jj);
then you have a newline at the start of your output (often a good thing) and then you don't need the if statement later - you just don't have a newline printed at the end of the line (because it will be printed at the start...)
There are marginally more efficient ways of doing this that would involve no if statements at all - but these all come at the expense of less readable code. For example, here is a "no loop unrolling and no additional if statements" version of the code:
http://codepad.org/01qPPtee
#include <stdio.h>
int main(void) {
int ii, jj;
ii = 0;
while(1) {
jj = 0;
while(1) {
printf("%d", jj); // include the space before the number printed
jj++;
if(jj<4) printf("."); else break;
}
ii++;
if(ii<2) printf("*\n"); else break;
}
return 0;
}
Output:
0.1.2.3*
0.1.2.3
Basically I have taken the functionality of the for loop and made it explicit; I also use a . rather than a and "*\n" rather than "\n" to show in the printout that things behave as expected.
It does what you asked without extra evaluation of the condition. Is it more readable? Not really...
If it really bothers you, you can unroll your loops a little so that you treat the last item as a special case:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 1; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu\n", j);
}
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu", j);
return 0;
}
#include <stdio.h>
int main(){
unsigned short num = 0, to=8;
while(num < to){
printf("%hu", num++);
if(num < to)
putchar(num % 4 == 0 ? '\n' : ' ');
}
#if 0
do{
printf("%hu", num++);
}while(num < to && putchar(num % 4 == 0 ? '\n' : ' '));
#endif
return 0 ;
}
Well, to try to answer your question, here's how I would do it:
for (i = k = 0; i < 2; i++){
if (i > 0) printf("\n");
for (j = 0; j < 4; j++, k++){
if (j > 0) printf(" ");
printf("%d", k);
}
}
I do it this way because I want to be sure every line but the first starts with a \n, and every item is separated by a space from the one before it.
Also, I do not want the row and column position to be intimately tied to the content of what is being printed.
In terms of performance, keep in mind that these if statements cost about 1 cycle, while each character printed costs at least hundreds if not thousands. printf goes through many layers of system calls to interpret its format string, build a buffer, send the buffer to the system I/O routines, which then cause repainting and scrolling of the console window. Get the idea?
DO NOT WORRY about performance unless you know you have a problem.
Then, don't guess. Use a diagnostic. Here's what I do.