Pattern Printing – 36

Print this pattern shown in the image below using recursion.

2(1)

This was for odd string length.The lower image shows for even string length.

2

This problem has to be solved using recursion. Whenever writing recursion we would suggest you to keep two conditions in mind, and those two conditions

  1. Terminating Condition or Base condition
  2. And Recursive Condition

For printing this pattern we have to divide it into Reverse V Shape Pattern and V Shape Pattern.
First the function for Reverse V Shape Pattern

void reverseVshape(char string[100],int low,int high){
	
	int length=strlen(string);
	int i;
	
	if(low<high){
	//Breaking Condition
		return;
		
	}else{
	//Recursive Condition 
	
		//Recursive Call
		reverseVshape(string,low+1,high-1);
		
		//Prints a row
		for(i=0;i<length;i++){
			
			if(i==low||i==high){
				//Prints Characters
				printf("%c",string[i]);
			
			}else{
				//Prints '*'
				printf("*");
				
			}
		}
		
		printf("\n");
	}
}

And now function for V Shaped Pattern

void Vshape(char string[100],int low,int high){
	
	int length=strlen(string);
	int i;
	
	if(low<high){
	//Breaking Condition	
		return;
	
	}else{
	//Recursive Condition 
	
		for(i=0;i<length;i++){
			if(i==low||i==high){
				//Prints Characters
				printf("%c",string[i]);
				
			}else{
				//Prints '*'
				printf("*");
				
			}
		}
		
		printf("\n");

	
		//Recursive Call
		Vshape(string,low+1,high-1);
		
	}
}

Here both functions takes 3 parameters

  1. The input string
  2. Low index which starts from left and moves to right
  3. High index which starts from right and moves to left

High index and low index are used for printing the characters as well as for breaking condition. The image below explains the working of recursion, function of both indices and also how the breaking condition works.

doubt16-1

#include&lt;stdio.h&gt;
#include&lt;string.h&gt;	/* strlen() */

//This function prints Reverse V Shape
void reverseVshape(char string[100],int low,int high){
	
	int length=strlen(string);
	int i;
	
	if(low<high){
	//Breaking Condition
		return;
		
	}else{
	//Recursive Condition 
	
		//Recursive Call
		reverseVshape(string,low+1,high-1);
		
		//Prints a row
		for(i=0;i<length;i++){
			
			if(i==low||i==high){
				//Prints Characters
				printf("%c",string[i]);
			
			}else{
				//Prints '*'
				printf("*");
				
			}
		}
		
		printf("\n");
	}
}

//This function prints V Shape
void Vshape(char string[100],int low,int high){
	
	int length=strlen(string);
	int i;
	
	if(low&gt;high){
	//Breaking Condition	
		return;
	
	}else{
	//Recursive Condition 
	
		for(i=0;i<length;i++){
			if(i==low||i==high){
				//Prints Characters
				printf("%c",string[i]);
				
			}else{
				//Prints '*'
				printf("*");
				
			}
		}
		
		printf("\n");

	
		//Recursive Call
		Vshape(string,low+1,high-1);
		
	}
}

int main(){
	char input[100];
	
	printf(&quot;Enter String for the pattern\n&quot;);
	scanf("%s",input);
	
	int length=strlen(input);
	
	reverseVshape(input,0,length-1);
	
	Vshape(input,0,length-1);
	
	return 0;
}

Pattern Printing – 35

1

This pattern is almost similar to a pattern we discussed earlier. So I recommend you to go through this first : http://wethecomputerguys.com/2014/05/22/printing-pattern-8/

In this pattern an extra input ‘seed’ is taken which denotes the starting point. The example I mentioned earlier has a default seed of 0.

Also at every stage while printing we take modulo 10 since after 9 we want 0 to be printed.

For loops refer the above pattern it’s the same.



#include<stdio.h>

int main(){
	int seed,rows,i,j;
	printf("Enter the value of seed:\n");
	scanf("%d",&seed);

	printf("Enter number of rows:\n");
	scanf("%d",&rows);
	

	for(i=0;i<rows;i++){
		for(j=0;j<=i;j++){
			printf("%d",(seed++)%10);
		}
		printf("\n");
	}
	
	return 0;
}

Program to check if it is an integer and within certain range

Write a program that only allows the user to only input an integer and test whether it lies in certain limit.

In this program we will take input from user as string then convert it into integer using atoi() function. And the check whether it lies in the certain limit.

atoi

  • atoi function is available in stdlib.h
  • It takes char array as input and returns int
  • While converting if the char array converted into int it returns 0
  • If it is valid number then it returns the number in int form

After we get int from atoi function we check whether it lies in our range.



#include<stdio.h>
#include<stdlib.h>		//For atoi

#define LOWERLIMIT 1	//Change lower limit according to requirement
#define UPPERLIMIT 10	//Chnage upper limit according to requirement

//This function returns -1 if array does not contain a valid number
//				returns 0 if number is out of range
//				returns 1 if number satisfies 
int checkIntegerRange(char array[100]){
	
	int result=atoi(array);
	
	if(result==0){
		
		printf("Not a valid number \n");
		return -1;
		
	}else{
		if( LOWERLIMIT<=result && result<=UPPERLIMIT ){
			
			printf("Number is valid\n");
			return 1;
			
		}else{
			
			printf("Number is not between %d-%d\n",LOWERLIMIT,UPPERLIMIT);
			return 0;
			
		}
		
	}
	
}

int main() {
	char input[100];
	scanf("%s",input);
	int returnValue=checkIntegerRange(input);
	
	if(returnValue==-1){
		/* do something */
	}else if(returnValue==0){
		/* do something */
	}else if(returnValue==0){
		/* do something */
	}
	
	return 0;
}

Pattern Printing – 34

doubt15-0

If we look closely the top half of the pattern repeats itself but in reverse order. So we will divide this pattern into two halfs as shown below.

doubt15-1

As the pattern reverses itself so we just have to write code for top half and the just reverse the outer loop and we get the lower half( this can be seen if we observe the outer loop of both the halfs ).

And while printing we place the row number on odd column number  and ‘*’ on even column number. This can be observed in the pattern below.

doubt15-2

The top row in grey color marks the column number and the column on left marks row number.

#include<stdio.h>

int main(){

	int n;

	printf("Enter number of rows\n");
	scanf("%d",&n);

	int i,j;
	
	for( i = 1 ; i <= n ; i++ ){
	//Outer loop for Top half
	
		for( j = 1 ; j<= 2*i-1 ; j++ ){

			if( j%2 == 1 ){
			//For odd column numbers
			
				printf("%d",i);
				//Prints the row number

			}else{
			//For even column numbers
			
				printf("*");
				//Prints *

			}

		}

		printf("\n");

	}
	
	
	for( i = n ; i >= 1 ; i-- ){

		for( j = 1 ; j <= 2*i-1 ; j++ ){

			if( j%2 == 1 ){
			//For odd column numbers
			
				printf("%d",i);
				//Prints the row number
				
			}else{
			//For even column numbers
			
				printf("*");
				//Prints *
				
			}

		}

		printf("\n");

	}
	
	return 0;
}

Pattern Printing – 33

1

For the pattern above we divide it into 2 parts:
– Left maroon right angled triangle.
– Right purple right angled triangle.

- Firstly take input of number of rows(n).

-For each row in the pattern(i):
– Print spaces. (n-i)
– Print part of left right angled triangle. (from i to i*2 – 1)
– Print part of right right angled triangle. (i*2 – 2 to i)

- New Line

2

#include <stdio.h>
int main(){
	
	int n,i,j;
	printf("Enter number of rows:\n");
	scanf("%d",&n);
	for(i=1;i<=n;i++){
		
		// Print spaces
		for(j=1;j<=n-i;j++){
			printf(" ");
		}
			
		// For left part.
		for(j=i;j<=(i*2)-1;j++){
			printf("%d",j);
		}
		
		
		// For right part.
		for(j=(i*2)-2;j>=i;j--){
			printf("%d",j);
		}
		
		// Newline
		printf("\n");
			
	}
				
	return 0;
}


PATTERN PRINTING – 32

doubt14

To code this pattern we will divide it into 5 parts as shown below. We will individually look into the code for each part and the combine it to print this pattern.

Part 1

doubt14-1

The part 1 is highlighted int he figure. This pattern is quiet similar to the Printing Pattern 3. https://www.youtube.com/watch?v=2CTeLMqzuXU This link contains the detailed explanation for these kinds of pattern.

for(i=1;i<=n;i++){

        for(j=n-i;j>=1;j--){
            printf("  ");

        }
        for(k=1;k<=2*i-1;k++){

            printf("*");

        }

        printf("\n");

    }

Part 2

doubt14-2

In this part we print spaces on the left and the the rectangle consisting of stars ‘*’

int t=n/2; //height of the rectangle
	for(i=1;i<=t;i++){

		for(j=n-t;j>=1;j--){

                        //prints spaces on left
			printf("  ");

		}

		for(k=1;k<=2*t-1;k++){

                        //prints the stars in the rectangle
			printf("*");

		}
		printf("\n");
	}

Part 3

doubt14-3

In this part we print ‘-‘

t++;//Incremented to match pattern requirements
	
	for(j=n-t;j>=1;j--){
			//prints spaces
			printf("  ");
			
	}
	
	for(k=1;k<=2*t-1;k++){
		//prints the central line
		printf("-");
		
	}
	
	printf("\n");
	
	t--;//To return to original value which was changed above
	

Part 4
doubt14-4
This is same as part 2

for(i=1;i<=t;i++){
		
		for(j=n-t;j>=1;j--){
			
			printf("  ");
		}
		
		for(k=1;k<=2*t-1;k++){
			
			printf("*");
		}
		
		printf("\n");
	}
	

Part 5
doubt14-5
This is similar to Part 1 its just reversed. This is evident from the outer loop.

for(i=n;i>=1;i--){
		
		for(j=n-i;j>=1;j--){
			
			printf("  ");
		}
		
		for(k=1;k<=2*i-1;k++){
			
			printf("*");
		}
		
		printf("\n");
	}
	

An when we merge this together we the the complete pattern.

#include<stdio.h>
int main(){
    int n;
    printf("Enter the number of rows for triangle\n");
    scanf("%d",&n);
    int i,j,k;
    for(i=1;i<=n;i++){
        for(j=n-i;j>=1;j--){
            printf("  ");
        }
        for(k=1;k<=2*i-1;k++){
            printf("*");
        }
        printf("\n");
    }
    
    //upper box
    int t=n/2;//dimetion of the square
    for(i=1;i<=t;i++){
        for(j=n-t;j>=1;j--){
            printf("  ");
        }
        for(k=1;k<=2*t-1;k++){
            printf("*");
        }
        printf("\n");
    }
    
    //for the central line
    
    t++;//Incremented to match pattern requirements
    
    for(j=n-t;j>=1;j--){
            //prints spaces
            printf("  ");
            
    }
    
    for(k=1;k<=2*t-1;k++){
        //prints the central line
        printf("-");
        
    }
    
    printf("\n");
    
    t--;//To return to original value which was changed above
    
    //lower box
    for(i=1;i<=t;i++){
        
        for(j=n-t;j>=1;j--){
            
            printf("  ");
        }
        
        for(k=1;k<=2*t-1;k++){
            
            printf("*");
        }
        
        printf("\n");
    }
    
    //lower triangle
    for(i=n;i>=1;i--){
        
        for(j=n-i;j>=1;j--){
            
            printf("  ");
        }
        
        for(k=1;k<=2*i-1;k++){
            
            printf("*");
        }
        
        printf("\n");
    }
    
    return 0;
}

Program to find Minimum Positive even number

Find for the lowest positive even integer.

You can input numbers whenever you want. But when you a negative number, it will stop asking and find the lowest positive even integer.

Logic:
– We assume that the minimum positive even number is 100000 and the user enters numbers which are less than 100000.
– For this we create a variable min and initialize it to 100000.
– Now take the input of numbers using an infinite loop.
– For each number(n)
– Check if n is greater than 0 ie positive. (n>0)
– Check if n is even(n%2==0)
– Check if n is less than current min.
– If all the above 3 condition is true then make n as current minimum.
– Else if n is negetive then stop by breaking the infinite loop
– if min= 100000 then the user entered the 1st number negetive.
– else print current minimum.

(NOTE: The logic works only if user enters numbers less than 100000.)

#include <stdio.h>
int main(){
	
	// Assume min to be current minimum value and initialize it to 100000.
	int n,min=100000;
	printf("Enter Numbers\n");
	
	// Infinite loop.
	while(1){
		scanf("%d",&n);
		
		//n>0 -> Positive n%2==0 -> Even n Number is less than current 
		if(n>0 && n%2==0 && n<min){
			// Make n as current minimum value
			min=n;
			
			// n<0 -> Negetive
		}else if(n<0){
			// if the 1st number is negetive.
			if(min==100000)
				printf("There is no minumum positive even number\n");
			else{
				// Print current minimum.
				printf("Minimum Positive even number is: %d",min);
			}
			break;
		}
	}
			
	return 0;
}


PATTERN PRINTING – 31

doubt13

This pattern is derived from https://www.youtube.com/watch?v=c7OYcRqzTco this pattern.
We highly suggest you to go through the pattern.
In this pattern instead of printing ‘*’ we print ‘&’ and we only print the first and last column
for all the rows except the last row, where we print it as it was in the video.

#include<stdio.h>

int main(){
    int n;
    
    printf("Enter Number of Rows\n");
    scanf("%d",&n);
    
    int i,j,k;
    
    for(i=1;i<=n;i++){
    
        for(j=n-i;j>0;j--){
            
            //prints spaces on the left hand side    
            printf(" ");
        
        }
        for(k=1;k<=i;k++){
            
            if(k==1||k==i||i==n){
            
                //k==1 --> first column
                //k==i --> last column
                //i==n --> last row
                //if this condition is satisfied then only print &
            
                printf("& ");
            
            }else{
            
                //else print spaces
                printf("  ");
            
            }
        }
        
        printf("\n");
    
    }
    
    return 0;
}

Previous Pattern

PATTERN PRINTING – 30

1

This pattern combination of 2 basic right angled triangle.
It would be much easier for you to understand this pattern if you know basic right angled triangle well.
I suggest you to watch this video first : http://wethecomputerguys.com/2014/02/27/c-practical-and-assignment-programs-pattern-printing-1/

So by now we know how to print a right angled triangle.
To print the above pattern we divide the figure in 3 parts as shown in the figure below:
2

The 3 parts are:
– The red triangle containing stars.
– The central blue region.
– The yellow triangle containing stars.

Logic for the code:

- Firstly we take input of number of rows(n)
– For each row(i : i goes from 0 to n-1)
– Print stars(number equal to row number).
– Print spaces(n-i-1).
– Print stars(number equal to row number).
– Newline.

#include<stdio.h>;
 
int main(){
   	int n,i,j;
	printf("Enter number of rows\n");
	scanf("%d",&n);
	
	// For each row
	for(i=0;i<n;i++){
		
		// PRint stars
		for(j=0;j<=i;j++)
			printf("*");
			
		// Print spaces
		for(j=0;j<n-i-1;j++)
			printf(" ");
			
		// Print stars
		for(j=0;j<=i;j++)
			printf("*");
			
		// New Line
		printf("\n");
	}
    return 0;
}

Previous Pattern :

PATTERN PRINTING – 29 (Spiral Pattern)

1

The pattern we need to print is in shape of square spiral (it starts with 1 at the top left corner and moves inwards increasing the count.) The figure above thus shows 1 at the top left corner and 25 at the centre.

The pattern can be thought as a 2-D matrix or a 2-D array. So we first represent the numbers in an 2-D array starting with (0,0) as shown in the figure below.

2

To store it in an 2-D array we need to traverse in an sprial or in loops. The traversal begins with the number 0 i.e. the outer loop is traversed first and then moving inwards. The figure below shows the traversals in different colors.

3

The above pattern requires total of 3 traversals.
– Firstly the red outer traversal.
– Then the second yellow and last the blue traversal.

Logic for the code:

- Firstly we take input of size of matrix(n).
– Number of traversals equals (round = n/2 Note: For n=5 ; traversals = 3 and for n=4 traversals = 2)
– Create a variable count=1
– For each traversal(i) (starting 0 till less than round)
– Store in array the upper row (from (i,i) to ((i, n-i-1) )) by incrementing the count.
– Store in array rightmost column (from (i+1, n-i-1) to (n-i-1, n-i-1) [We didn't start from (i,n-i-1) since we need to move to the next row]) by incrementing the count.
– Store in array bottom row (from (n-i-1, n-i-1) to (n-i-1, i)) by incrementing the count.
– Store in array leftmost column(from (n-i-2, i) to (i+1, i)) by incrementing the count.

- Now we need to print the 2-D array.



#include<stdio.h>
#include<math.h>

int main(){
   	int arr[20][20],n,t,i,max=0,index,j;
        printf("Enter size of matrix\n");
   	scanf("%d",&n);
   	int count=1;
   	
   	// Number of traversals
   	int round = ceil((double)n/2);
   	
   	// For each traversal
   	for(i=0;i<round;i++){
   	
   	   // Topmost row
   	   for(j=i;j<=n-i-1;j++){
   	   		arr[i][j]=count++;	
   	   }
		
		// Rightmost column
		for(j=i+1;j<=n-i-1;j++){
			arr[j][n-i-1]=count++;
		}
		
		// Bottommost row
		for(j=n-i-2;j>=i;j--){
			arr[n-i-1][j]=count++;
		}
		
		// Leftmost column
		for(j=n-i-2;j>i;j--){
			arr[j][i]=count++;
		}
			  	
   	}
   	
   	
   	// Print array
   	for(i=0;i<n;i++){
   		for(j=0;j<n;j++)
   			printf("%d  ",arr[i][j]);
   		printf("\n");
   	}
   	
	return 0;
}
Follow

Get every new post delivered to your Inbox.