printing triangle using recursion in c without loop or multiplication - c

I'm supposed to print a triangle int tri(int rows) in c using recursion without multiplication or loops. The triangle should have one * in the 1st row, two ** in the 2nd row, three *** in the 3rd row and so on...
here's what I tried and what seems to work in other peoples code, but not in mine. I sadly cannot see the error yet:
#include <stdio.h>
int triangle(int rows){
if(rows >= 0){
return 0;
}
else if(rows == 1){
printf("*");
return 1;
}
else{
printf("*");
return rows + triangle(rows-1) ;
}
}
int main()
{
triangle(5);
return 0;
}
I'm guessing it has something to do with the printing part, I thought about making an own variable for that but since I'm not allowed to use multiplication, I don't know how I could describe it. I want to know what my logical problem is right here and how I could solve it easily.

Imagine that you had a function void line(n) that prints n asterisks on one line.
Then you could write
void triangle(int n)
{
// Print the smaller triangle first, if there should be one.
if (n > 0)
{
triangle(n-1);
}
// Then add the last line after the smaller triangle.
line(n);
}
All that remains is to add the lines:
void line(int n)
{
if (n <= 0)
{
// End of line.
printf("\n");
}
else
{
// Print an asterisk, and then the rest of the line.
printf("*");
line(n-1);
}
}

Here's a slightly different version which uses just one set of recursive calls.
The second recursive call is replaced by using the printf statement to simply output the desired number of stars on each line.
/* triangle.c */
#include <stdio.h>
void triangle(int num)
{
if (num > 1) {
triangle(num - 1);
}
printf("%.*s\n", num, "****************");
}
int main (void)
{
triangle(16);
return 0;
}

Related

How can I convert this code into a recursive function? Base case analysis

#include <stdio.h>
int main() {
int n;
printf("Enter width: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || (i + j + 1) == n) {
printf("X");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
How can I convert this code into a recursive function? I am having trouble with the "base case" I am trying to work with this line
void recursiveProblem(int num, int max) {
if (num <= (max / 2 + 1))
...
}
so if I reach halfway I can print the middle line and return it, but it's not working. This function will print a large X made from x's?
To solve tasks using recursion, you can use this pattern:
to solve the task:
check if you've reached a trivial case. If so:
do the trivial thing
otherwise:
split the task into smaller parts that look similar to the whole task
solve each of the smaller tasks by calling the function recursively
In your case the task is print_diagonals(width_of_the_square, current_line_number).
Defining this task by giving it a proper name and by finding out the parameters and their names is the most important part of solving this kind of problems. It's much easier to think about print_diagonals than about recursiveProblem since the names I've given carry lots of meaning and exactly describe their purpose.
The "trivial case" in this task can be either "print the line in the middle of the square" or "print the bottom line of the square". Both will work, and the programs will look similar. Try them both and then compare the resulting programs. The part these programs have in common is typical for recursive programs.
Using this information, you should be able to do your homework by yourself.
I don't understand why anyone would want to make this recursive. But this works.
#include <stdio.h>
void recurse(int i, int j, int n){
printf(i==j || i+j+1==n ? "X" : " ");
if (++j == n) {
printf("\n");
if (++i == n)
return;
j=0;
}
recurse(i, j, n);
}
int main(){
int n;
printf("Enter width: ");
scanf("%d",&n);
recurse(0, 0, n);
return 0;
}
If you'll notice, I move one if block right inside the printf statement using the ? : operator.
Also, notice that every single printf is called from it's own recurse function call, which is on top of every other function call on the stack. So if your stack is limited and n is large, you could run out of stack and crash. This is one reason recursive functions should only be used with caution.
Alternately, you could put the loop that increments j in the recursive function and only recurse to increment i. That would use a lot less stack.

Multiplication table - C

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.

C program function error

This code has to get coordinates and write them to the coords array, and also return the number of coordinates that have been entered.
The code has to stop once the user enters 0 0 but the code should not save it.
For example if I enter 1 2 3 4 0 0 the code will set the array to (1,2) (3,4).
But in this code when I enter 0 0 it show me error, and once I enter the numbers at first the print show me just zeros.
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
++row;
}
printf("%.3lf %.3lf", coords[row][0], coords[row][1]); /* TEST */
}
return row+1;
}
The problem is that when you print coords[row][0] and coords[row][1] you are actually sending to stdout the next coordinates which are not still entered by the user. You are sending to stdout undefined values and not the values you entered. The line printf("%.3lf %.3lf", coords[row][0], coords[row][1]); should be printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); And add the next to line \n otherwise the information printed is illisible.
Try this code
#include <stdio.h>
#include <stdlib.h>
#define DIM 2
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
row++;
}
printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); /* TEST */
}
return row+1;
}
int main(void)
{
double cords[5][2];
int n = 5;
coordinatesread(cords, n);
return 0;
}
Okey, let's see. The problem in your code is that you are incrementing the value of row before printing the values in coords[row][0]=columnin
You are not going to print a line if the values are both zero, so you can move this line:
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
Right before this one:
++row;
The new code should look like this:
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
++row;
}
}
return row+1;
}
PD:
Notice that your code does not work fine if you want to scan N valid coordinates, because the last one will be ignored. The problem is here:
while(row!=n-1)
If you have decided to use while loop instead of for, you should iterate until row = N. Let's suppose N = 3. If you want to scan 3 valid coordinates, the loop will iterate while N != 2. This will scan only two of them (when row = 0 and row = 1). Change it to:
while(row!=n)
In addition, when you are iterating over an array (or a table in this case), using for is better than while. Both are correct, but for is more stylized. If you change it, the code look like this:
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
for(int row = 0; i < n; i++)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
}
}
return row;
}

Printing a number in sequence using C - Algorithm

Sample pattern is given,
input : 16
output: 16 11 6 1 -4 1 6 11 16
If the input is 10, then program should print output as
10 5 0 5 10
Note: The above sequences decrement/increment by 5.
The challenge is to not declare any variables or loops. use only recursion.
I have tried with the following code.
void sequence(int input, int base){
input = input - (input > 0?5:-5); //main execution
printf("input:%d\n",input);
if(input == base)return;
sequence(input,base);
}
//for eg. input and base(initial Value) is 16. The above method recurse itself until input = base.
I can print upto this sequence (in Bold)
16 11 6 1 -4 1 6 11 16
How to complete the sequence. In the above method, in main execution line, i need to check condition as input = input - (input < 0?5:-5); to print the remaining sequence. But i am not sure how can i do this without any variables or loops. Is there any algorithm available or any other better solution.
Some example code to my comment, which would match if it doesn't have to be strictly left- or right-recursive:
void sequence(int n)
{
printf("%d ", n);
if (n > 0)
{
sequence(n-5);
printf("%d ", n);
}
}
Further notes:
1.) This seems to be about functional programming, where a key concept is that you can never assign a variable ... see how it is avoided here. (Strictly speaking, it's not functional because of the printf side effects)
2.) It's not strictly left- or right-recursive (meaning the recursion happens in the middle of evaluation), so it can't be easily transformed to something iterative.
It seems that the recursion should stop when it reaches 0 or below. So try this condition in you recursive function (reduced to only one argument):
void sequence(input) {
// print input
if (input > 0) {
// recursive call
sequence(input);
}
// print input again (sometimes...)
}
Update: Let's talks about Symmetry
For the sake of symmetry, also the reverse version of Felix's solution can be used
void sequence(int n)
{
if (n > 0) {
printf("%d ", n);
sequence(n-5);
}
printf("%d ", n);
}
Both feature a kind of asymmetry that seems not to fit to the palindromic structure of the problem, and there is another problem: the blemish of a trailing space. So let's introduce to you a obvious solution that deals with these tiny(?) flaws:
void sequence(int n)
{
if (n > 0) {
printf("%d ", n); sequence(n-5); printf(" %d", n);
} else {
printf("%d", n);
}
}
Use two different functions to cout up and down:
void down(int input, int base) {
printf("input:%d\n",input);
if(input > 0) down(input - 5, base);
else up(input + 5, base);
}
void up(int input, int base) {
printf("input:%d\n",input);
if(input == base) return;
up(input + 5, base);
}
Start the calculation by calling down.
Live Demo
The base case of your recursive code seems wrong. I think your code goes into infinite recursion the way it is. You can use a flag to achieve your sequence:
void sequence(int input, int base){
static int flag = 0;
//input = input - (input > 0?5:-5); //main execution, wrong
printf("input:%d\n",input);
input -= (flag == 0)?5:-5; //use flag for base case of sequence
if(input <= 0)
flag = 1;
if(input == base){
printf("input:%d\n",input);
return;
}
sequence(input,base);
}
#include <stdio.h>
using namespace std;
void printSequence(int input) {
printf("%d ", input);
if (input <= 0)
return;
printSequence(input - 5);
printf("%d ", input);
}
int main ()
{
int input = 0;
scanf("%d", &input);
printSequence(input);
return 0;
}

8 Puzzle with Backtracking

I was reading this book from Skiena, Programming Challenges and after the backtracking chapter there was a question about solving the 15-puzzle with backtracking, which I reduce it to 8-puzzle just experimenting. I have this recursive code and I am wondering whether it have a chance to find the solution ever. The code is kind of ugly (be warned):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int arr[20][20]={
{3,1,2},
{4,0,5},
{6,8,7}
};
int moveX[20]={1,1,1,0,0,-1,-1,-1};
int moveY[20]={0,1,-1,1,-1,0,1,-1};
int depth=0;
int findRow(){
int i,j;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(arr[i][j]==0){
return i;
}
}
}
}
int findCol(){
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(arr[i][j]==0){
return j;
}
}
}
}
void print(){
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%i ",arr[i][j]);
}
printf("\n");
}
printf("\n");
}
int isReady(){
if(arr[0]==1 && arr[1]==2 && arr[2]==3 && arr[3]==4 && arr[4]==5 && arr[5]==6 && arr[6]==7 && arr[7]==8){
return 1;
}
else return 0;
}
void perm(int row,int col,int n){
if(n>=9){
print();
if(isReady())
printf("Finished");
depth++;
return;
}
int i=0;int diffX,diffY,temp;
int r=findRow();
int c=findCol();
temp=arr[r][c];
arr[r][c]=arr[row][col];
arr[row][col]=temp;
for(i=0;i<8;i++){
diffX=row+moveX[i];
diffY=col+moveY[i];
if(diffX>=0 && diffX<4 && diffY>=0 && diffY<4){
perm(diffX,diffY,n+1);
}
}
temp=arr[r][c];
arr[r][c]=arr[row][col];
arr[row][col]=temp;
}
int main()
{
perm(0,0,0);
return 0;
}
My question is, is there a chance with this code to find the solution and second, can anybody how the puzzle can be solved in reasonable time?
You have five problems. First, the isReady function is incorrect. It should look like this:
int isReady(){
if(arr[0][0]==1 && arr[0][1]==2 && arr[0][2]==3 &&
arr[1][0]==4 && arr[1][1]==5 && arr[1][2]==6 &&
arr[2][0]==7 && arr[2][1]==8){
return 1;
}
else return 0;
}
Second, you are exceeding your puzzle bounds with diffX and diffY. You need to change this:
if(diffX>=0 && diffX<4 && diffY>=0 && diffY<4){
to this:
if(diffX>=0 && diffX<3 && diffY>=0 && diffY<3){
Third, your findRow function also exceeds the puzzle bounds. Change all of the 4 to 3.
Fourth, you should check your victory condition only after you have made your move. So move your victory check below the swap:
temp=arr[r][c];
arr[r][c]=arr[row][col];
arr[row][col]=temp;
// This victory check is now below the move.
if(n>=9){
print();
if(isReady())
printf("Finished");
depth++;
return;
}
Fifth, you should change your initial call from this:
perm(0,0,0);
to this:
perm(1,1,0);
The way you have it, you are always forcing a move to the upper left as your first move. The modified way keeps the 0 in the center so it doesn't force your first move. When I ran this code with all of the modifications I made, it found 3 solutions. When I further modified the code to check for solutions at any depth, it found 2 solutions at depth 8 and 3 solutions at depth 9.

Resources