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;
}

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;
}

In an array of integers verify whether a given element is a row-peak. An element is said to be row-peak if it is a row-wise local maxima i.e it is strictly greater than its adjacent row neighbours.

Input Format: The first line of input contains the size n of the array. Then n lines of input follow giving the contents of the array. The next line contains the number of test cases t. This is followed by t lines each of which contains the corresponding indices of the element which you have to verify.

Output Format: You must output “Yes” or “No” in a separate line for each test case. Output “Yes” if the corresponding test case holds the required property else print “No”.

Variable Constraints: The size of the array is smaller than 20. The contents of the array are integers in the range from -32768 to 32767.

/*

Logic:

- Firstly we take input of size of array and then the elements of array.
– Assume max=0 i.e. the element at 0th position is maximum.
– Take input of number of test case.
– For each test case i.e. index
– if index equals max optput yes
– if not output no.
*/


#include<stdio.h>
int main(){
   	int arr[20],n,t,i,max=0,index;
   	
   	// Input of size of array.
   	scanf("%d",&n);
   	
   	// Input of array elements.
   	for(i=0;i<n;i++){
   	   scanf("%d",&arr[i]);
   	   
   	   // Checking if current element is greater than our max
   	   if(arr[i]>arr[max])
   	   		max=i;
   	}
   	
	// Input of number of test case.
	scanf("%d",&t);
	
	// Input of number of test cases	
	for(i=0;i<t;i++){
		// Input of index
		scanf("%d",&index);
		
		// Comparison with index of max.
		if(index==max){
			printf("YES\n");
		}else{
			printf("NO\n");
		}	   	
   	
   }
   	
	return 0;
}

Write a program that asks the user to insert 10 numbers for an array. Program has to calculate and write which of those numbers are >=10


#include<stdio.h>
int main(){
   	int n,arr[10],i;
   	printf("Enter 10 numbers\n");
   	
   	// Input of 10 numbers and store in an array
   	for(i=0;i<10;i++){
   		scanf("%d",&arr[i]);
   	}
   	
   	printf("Numbers greater than 10 are:\n");
   	
   	for(i=0;i<10;i++){
   		
   		// Comparison with 10 and printing.
   		if(arr[i]>=10)
   			printf("%d\n",arr[i]);
   	}
   	
	return 0;
}

Program to find all the Armstrong Numbers from 1 to 1000

This code finds all the Armstrong Numbers from 1 to 1000
For what are Armstrong Numbers please refer this video
Link https://www.youtube.com/watch?v=OvANihsVDI8

#include<stdio.h>

//The logic is taken from the video mentioned above we highly suggest you to go through it.
int checkArmstrong(int num){
    int temp=num;
    int sum=0;
    while(temp!=0){

        int unitsPlace=temp%10;
        sum=sum+unitsPlace*unitsPlace*unitsPlace;
        temp=temp/10;

    }
    if(sum==num){

        return 1;//ie True

    }else{

        return 0;//ie False

    }
}

int main(){

	int i;
	printf("Armstrong Numbers are\n");

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

		//Loops from 1 to 1000
		int isArmstrong=checkArmstrong(i);

		//chcks if it is Armstrong number

		if(isArmstrong==1){//ie True
			printf("%d\n",i);

		}

	}

	return 0;
}

Pattern Printing 28

doubt9

Write a program to print the diamond pattern shown above.

Logic: 1)We divide the above pattern into Upper Half and Lower Half.

2)Divide each Half into Left Half and Right Half as shown below.

doubt9-2

3)Now that we have divided into smaller pattern we start coding.

 

#include<stdio.h>

void main(){

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

    int i,j,k,l,m;

    //Upper Half of the diamond pattern
    for(i=1;i<=n;i++){//Increasing Rows

        //Prints spaces
        for(j=1;j<=n-i;j++){
            printf(" ");
        }

        //Number to be printed on the screen
        int printNo=n;

        //Loop for Left Half
        for(k=1;k<=i;k++){
            printf("%d",printNo);
            printNo--;
        }

        //Number to be printed on the screen
        printNo=n-i+2;

        //Loop for Right Half
        for(l=1;l<i;l++){
            printf("%d",printNo);
            printNo++;
        }

        printf("\n");
    }

    //Lower Half of the diamond pattern
    //Inner Code in this loop is same as the above
    //only the loop decrements
    for(i=n-1;i>=1;i--){//Decreasing Rows

        //Prints spaces
        for(j=1;j<=n-i;j++){
            printf(" ");
        }

        //Number to be printed on the screen
        int printNo=n;

        //Loop for Left Half
        for(k=1;k<=i;k++){
            printf("%d",printNo);
            printNo--;
        }

        //Number to be printed on the screen
        printNo=n-i+2;

        //Loop for Right Half
        for(l=1;l<i;l++){
            printf("%d",printNo);
            printNo++;
        }

        printf("\n");
    }
}

 

 

Pattern Printing 27

doubt8

Write a program to print a rectangle whose length and breadth will be give by user. The output will look like the image shown above.

 

#include<stdio.h>
int main(){
    int length,width;
    printf("Enter length:");
    scanf("%d",&length);
    printf("Enter width:");
    scanf("%d",&width);
    int i,j;
    //This loop prints columns ie width
    for(i=1;i<=width;i++){
        //This loop prints rows ie length
        for(j=1;j<=length;j++){
            //Check if it lies on the border
            //i==1 --> means first row
            //i==width --> means last row
            //j==1 --> means first column
            //j==length --> means last column
            if(i==1||i==width||j==1||j==length){
                printf("*");
            }else{//Else print space
                printf(" ");
            }
        }
        //Goto next line
        printf("\n");
    }
    return 0;
}

Pattern Printing 26

Untitled

Write a program to do the following :
a) Take height and base length as the input
b) Based on the height and base length, print n lines in output (where n=height) such that they form a pattern in the shape of a regular “inverted” trapezium
c) Each line should form an Arithmetic Progression with the starting element = (row_number) and common difference (1). Take modulo 10 for numbers greater than 9

Input Format : Two integers separated by a space – First integer is the height of the pattern and the second integer is the base_length of the pattern

Output Format : Output should contain lines equal in number to the height of the pattern with each line representing a row.Display the pattern with no extra empty lines above or below the pattern or in between successive rows of the pattern.

Figure shows the output for input 5 14


/*
Logic:
- Take input of height and base_length.
- For each row starting with row number 0 till less than height.
	- Print spaces equal to row number.
	- Print numbers starting with row_number + 1 and increment by 1 . Mod this by 10 and print. Total numbers in a row equals base_length.
	- Decrement base_length by 2.
	- New Line.
*/

#include<stdio.h>
int main(){
	
	int height,base_length,i,j;
	printf("Enter height and base length\n");
	scanf("%d %d",&height,&base_length);
	
	// loop for each row
	for(i=0;i<height;i++){
		
		// Print spaces
		for(j=0;j<=i;j++)
			printf(" ");
			
		// Print numbers starting with row number	
		for(j=0;j<base_length;j++)
			printf("%d",(i+1+j)%10);
			
		// Newline
		printf("\n");
		
		base_length-=2;
	}
	
	return 0;
}

C Practical and Assignment Programs-Pascal Triangle Shorter Code

#include<stdio.h>
int factorial(int n){
	if(n==1||n==0){
		return 1;
	}
	return n*factorial(n-1);
}
int nCr(int n,int r){
	return factorial(n)/(factorial(r)*factorial(n-r));//n!/(r!(n-r)!)
}
void main(){
	int n;
	printf("Enter number of rows\n");
	scanf("%d",&n);
	int i,j,k;
	for(i=0;i<n;i++){
		for(j=n-i;j>0;j--){
			printf(" ");
		}
		for(k=0;k<=i;k++){
			printf("%d ",nCr(i,k));
		}
		printf("\n");
	}
}

Prime Lovers

Well, I might not define What’s A prime Number..(A number divisible only by 1 and itself :P)

But what if i tell u to find all prime numbers below 100.

Fine..!! U can either find it manually or if u r smart Enough u will make Code for it!!Simple enough?

Naive Approach:

Here is a Pseudo Code for it:

Let n be a number To check for “Primality”:

start i from 2 to n-1

Check whether n is divisible by i or not

If(yes)

stop here..Number is Not prime.

if u reach till n-1 and it is not divisible then n is prime!!

A More Optimised Version:

start i from 2 to squareroot(n)

Seams to be Easy enough!!

But Might be too Boring for the computer too, to calculate for each number untill 100.

What if i tell u to calculate all Prime numbers below 10^6 ?(Yeah 10 raise to 6 :P)

Hmmm..Even this program will take a long time.

Well Dont be Disheartened!!

Here comes the Most exciting Part.

There is an Excellent Method To calculate all primes below a given large Number:

Sieve Of Eratosthenes:

Fun starts Here!!:

A step by step Approach:

Let N be a number Below which u want to find all Prime Numbers

  1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
  2. Initially, let p equal 2, the first prime number.
  3. Starting from p,Cut Down all Numbers(Except p) multiple of p. i.e. 2p, 3p, 4p, etc.; note that some of them may have already been marked.
  4. Find the first number greater than p that hasn’t been cut down. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.

Well to understand better here is an Example.

Find Primes Below 30.

First generate a list of integers from 2 to 30:

 2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

First number in the list is 2; cross out every 2nd number in the list after it (by counting up in increments of 2), i.e. all the multiples of 2:

 2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Next number in the list after 2 is 3; cross out every 3rd number in the list after it (by counting up in increments of 3), i.e. all the multiples of 3:

 2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Next number not yet crossed out in the list after 3 is 5; cross out every 5th number in the list after it (by counting up in increments of 5), i.e. all the multiples of 5:

 2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Next number not yet crossed out in the list after 5 is 7; the next step would be to cross out every 7th number in the list after it, but they are all already crossed out at this point, as these numbers (14, 21, 28) are also multiples of smaller primes because 7*7 is greater than 30. The numbers left not crossed out in the list at this point are all the prime numbers below 30:

 2  3     5     7           11    13          17    19          23                29

(Images- Wiki)

Well this might seam easy !!But tricky while programming!!

Pseudo Code:

“isPrime” is a boolean (True or False) Array

Initialize all values to true.(Assuming All values uptil k is a prime Number)

At the end of Code if u want to find if ‘x’ is prime or not,Just check bool value of isPrime[x]. If true then its prime else not a prime.

1)isPrime[0] = false

2)isPrime[1] = false

3)for i = 2 to K do

    isPrime[i] = true  //Initializing all values to true

4)for i = 2 to sqrt(K) do 

    if isPrime[i] then  

        for j = i^2, i^2+i, i^2+2*i, …, k: //Note that it starts from i square and not 2*i.They have already been checked

            

             isPrime[j] = false  //they all are Not Primes

All the true values in array suggests that its an prime number (Since it was not a multiple of any number!!!!)

The Two Advantages of this method:

1)Simple approach and Faster than the Naive one.

2)Easily finds the no of Primes below A certain number .

As we have Precalculated all primes, its called memoization,and it can be accessed as and when required.

Just for comparing the difference in time taken:-

naive algo : O(n^2) or O(n*sqrt(n))
sieve : O(n(log n)(log(log n)))

which is a big difference for large values of n.

Here is the implementaion:

// This code checks whether a given number is prime or not.

#include<iostream>;
    
using namespace std;
     
int main(){
     
    bool isPrime[1000007];
    isPrime[0] = false;
    isPrime[1] = false;
    for (int i = 2 ;i<1000005;i++)
    isPrime[i] = true;
    for (int i = 2;i*i<1000005;i++){
        if(isPrime[i]){
        for (int j = i * i;j<1000005;j+=i)
            isPrime[j] = false;
        }
    }

     // Here 1000003 is checked for being prime.
     // To check any other number replace 1000003 with it.
    if(isPrime[1000003]){
        cout<<"Yep it's prime!!!";
    }else{
        cout<<"Nahh it's not prime!!!";
    }
     
     
    return 0;
}    


Seive Approach : Seive

Any comments are welcomed.Happy Coding :)

Follow

Get every new post delivered to your Inbox.