First steps in ruby. Printing a triangle of stars
I’m going to try and write some simple ruby programs. Here’s the first one. It prints a triangle of stars like this:
* ** *** **** ***** ****** ******* ******** ********* ********** ***********
And here is the code:
star_string = "*" 10.times do puts star_string star_string = star_string + "*" end
I hope you can understand it. The program creates a string called “star_string”. Then it loops 10 times. Each time it loops it prints (puts) out star_string, and adds another * to the string. That way star_string gets longer and longer.
I’m also going to show you how this is done in C++. If you don’t want to learn C++ you don’t need to look at this. But C like languages are so common it’s worth at least gaining some familiarity with the syntax.
#include
#include
using namespace std;
int main() {
string star_string = “*”;
for(int n=0;n<10;n++) { cout << star_string << endl; star_string = star_string + "*"; } } [/sourcecode] Can you modify the program so it prints more than one triangle, like this? [sourcecode language="html"] * ** *** **** ***** ****** ******* ******** ********* ********** * ** *** **** ***** ****** ******* ******** ********* ********** [/sourcecode] Post your solution in the comments sections below. Everytime someone posts a solution, I'll try to post a new example and problem the next day. The part 2 is now HERE.