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 :)

Pattern Printing 25

doubt7

#include<stdio.h>
int main(){
    printf("Enter number of rows\n");
    int n;
    scanf("%d",&n);
    int i,j,k;
//loop for number of rows
for(i=1;i<=n;i++){
for(j=1;j<i;j++){
//prints the spaces on left
printf(" ");
}

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

//checks if it is first or last row and prints star
if(k==1||k==n-i+1){
printf("* ");
}else{

//prints spaces in between
printf("  ");
}
}

//goes to next line
printf("\n");
}
return 0;
}

Pattern Printing 24

Untitled

/*
Logic:
- We divide the problem in 4 parts i.e upper 1 , remaining upper triangle , lower triangle except last 1 , last 1.
- Firstly take input of number of rows(input should be an odd number).
- Initialize variables half=num of rows/2 and print=0 
- For upper 1
	- Print spaces
	- Print 1
- For remaining upper triangle.
	- Print spaces
	- Print number(number equals the value of print variable)
	- Print space
	- Print number(number equals the value of print variable)
	- New line
- If value of print is 0 make it 1 : if not make it 0.
- Repeat the same procedure for the lower part.
*/

#include<stdio.h>
int main(){
    int n,i,j,half,print=0;
    printf("Enter number of rows.\n");
    scanf("%d",&n);
    half = n/2;
    
    // For upper 1
    for(i=0;i<half;i++)
    	printf(" ");
    printf("1\n");
    
    // For upper triangle except 1.
    for(i=1;i<=half;i++){
    	
    	// print spaces
    	for(j=1;j<=half-i;j++)
    		printf(" ");
    		
    	// Print number(value of variable print)
    	for(j=1;j<=i;j++)
    		printf("%d",print);
    	// Print space
    	printf(" ");
    	
    	// Print number(value of variable print)
    	for(j=1;j<=i;j++)
    		printf("%d",print);
    		
    	// New line
    	printf("\n");
    	
    	// Change value of variable print
    	if(print==0)
    		print=1;
    	else
    		print=0;
    }
    
    // For lower part of figure.
	for(i=1;i<=half-1;i++){
    	for(j=1;j<=i;j++)
    		printf(" ");
    	for(j=1;j<=half-i;j++)
    		printf("%d",print);
    	printf(" ");
    	for(j=1;j<=half-i;j++)
    		printf("%d",print);
    	printf("\n");
    	if(print==0)
    		print=1;
    	else
    		print=0;
    }
    
    for(i=0;i<half;i++)
    	printf(" ");
    printf("1");
	     
    return 0;
}

Take input till the user enters 30 integers and print its sum using an infinite loop.

/*
Illustration of the use of break statement.

Take input till the user enters 30 integers and print its sum using an infinite loop.

Logic:
- Initialize variables sum and count to 0.
- Inside an infinite while loop.
	- Take input of num.
	- Increment count.
	- Add input to sum.
	- Check if count is equal to 30 : if yes use break statement.
- Print sum.
 */
 
#include<stdio.h>
int main(){
	int i,sum=0,count=0;
	printf("ENter integers\n");
	while(1){
	 
		scanf("%d",&i);
		count++;
		sum+=i;
		if(count==30)
		break;
	}
	 
	printf("The sum of your 30 numbers is %d.",sum);
	return 0;
}

Pattern Printing 23

Untitled

/*
Logic:
– Take input of number of rows(n).
– For each row(i) (row number starting with 0)
– Print spaces equal to row number.
– Print numbers starting with total-rownum(n-i) and decrementing till it’s greater than 0 along with a blank space.
– New Line.
*/

#include <stdio.h>
int main(){
	int i,j,n;
	printf("Enter number of rows\n");
	scanf("%d",&n);
	
	// loop for each row
	for(i=0;i<n;i++){
		
		//print spaces
		for(j=0;j<i;j++)
			printf(" ");
		
		// print numbers along with a blank space
		for(j=n-i;j>0;j--)
			printf("%d ",j);
			
		// New line
		printf("\n");
	}
	
	return 0;
}

C Programming Language Tutorial-Lect 24 Arrays And Pointers

This tutorial explains the concept of pointers in C. Pointer notation to access the elements of the array is explained in this tutorial. Also how 1-D and 2-D arrays are placed in consecutive memory
blocks is explained in this lecture.


/*
Print 1-D array using pointer notation.
*/
#include<stdio.h>
int main(){
	int arr[]={2,1,3,5,1,9};
	int i;
	
	for(i=0;i<6;i++){
		printf("%d  ",*(arr+i));
	}
			
	return 0;
}


/*
Print 2-D array using pointer notation.
*/
#include<stdio.h>
int main(){
	int arr[3][2]={{1,2},{3,4},{5,6}};
	int i,j;
	
	for(i=0;i<3;i++){
		for(j=0;j<2;j++){
			printf("%d  ",*(*(arr+i)+j));
		}
		printf("\n");
	}
			
	return 0;
}

Pattern Printing 22

Untitled

/*
Logic:
1.Take input of number of rows.
2.create a count variable and initialize it to 0.
3.For each row
-Number of elements is equal to row number
the 1st row has 1 element 2nd has 2 and so on…
-for each element print character 'A' + count ('A' + 1 = 'B' ; 'A' + 3 = 'D').
-increment count.
4.new line
*/

#include<stdio.h>
int main(){
int n,i,j,cnt=0;
printf("Enter number of rows\n");
scanf("%d",&n);
for(i=1;i<=n;i++){
 
// printing each row
for(j=1;j<=i;j++){
printf("%c ",'A' + cnt++);
}
printf("\n");
}
return 0;
}

Pattern Printing 21

Untitled

/*
Logic:
- Firstly we take input of size(n).
- Print stars for upper horizontal line. Number of stars equals n.
- Breakline.
- For slanting edge i.e for each row(i) : 
	- Print spaces (n-i-2).
	- Print star (1). 
	- Breakline.
- Print stars for lower horizontal line. Number of stars equals n.

*/

#include<stdio.h>

int main(){
	int n,i,j;
	printf("Enter Size\n");
	scanf("%d",&n);
        // print upper Horizontal line of stars.  
	for(i=0;i<n;i++)
		printf("*");
	printf("\n");

        // print slant edge.
	for(i=0;i<(n-2);i++){
		
                // print spaces
		for(j=0;j<n-i-2;j++)
			printf(" ");
               
                // print star.   
		printf("*\n");
	}
	
        // print bottom Horizontal line of stars.
	for(i=0;i<n;i++)
		printf("*");
		
	return 0;
}

Pattern Printing 20

Untitled

/*
Logic:
- Firstly we take input of number of rows(n).
- For each row(i) starting with row number 1.
	- Print number of spaces equal to (n-i).
	- Print numbers and underscore(_) where numbers go from 1 to row number.
	- Breakline.
*/

#include<stdio.h>

int main(){
	int n,i,j,count=0;
	printf("Enter number of rows.\n");
	scanf("%d",&n);	
	for(i=1;i<=n;i++){
		
		//print spaces
		for(j=0;j<n-i;j++)
			printf(" ");
		
		//printing integer followed by underscore(_)
		for(j=1;j<i;j++)
			printf("%d_",j);
		
		//print the last integer.
		printf("%d",i);
		
		//Breakline
		printf("\n");
	}
		
	return 0;
}
Follow

Get every new post delivered to your Inbox.