Factorial of large Numbers

WeTheComputerGuys- Factorial

The value of factorial is very big integer and so cannot be stored in an integer data type. So we store the numbers as strings and multiply 2 strings . Multiply two strings the way we multiple 2 numbers manually on a paper.

WeTheComputerGuys- Factorial


#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10000

// Function to multiple 2 big numbers in the same way
// manual multiplication is done

char * multiply(char a[],char b[]){
    static char mul[MAX];
    char c[MAX];
    char temp[MAX];
    int la,lb;
    int i,j,k=0,x=0,y;
    long int r=0;
    long sum = 0;
    la=strlen(a)-1;
        lb=strlen(b)-1;
   
        for(i=0;i<=la;i++){
                a[i] = a[i] - 48;
        }

        for(i=0;i<=lb;i++){
                b[i] = b[i] - 48;
        }

    for(i=lb;i>=0;i--){
         r=0;
         for(j=la;j>=0;j--){
             temp[k++] = (b[i]*a[j] + r)%10;
             r = (b[i]*a[j]+r)/10;
         }
         temp[k++] = r;
         x++;
         for(y = 0;y<x;y++){
             temp[k++] = 0;
         }
    }
   
    k=0;
    r=0;
    for(i=0;i<la+lb+2;i++){
         sum =0;
         y=0;
         for(j=1;j<=lb+1;j++){
             if(i <= la+j){
                 sum = sum + temp[y+i];
             }
             y += j + la + 1;
         }
         c[k++] = (sum+r) %10;
         r = (sum+r)/10;
    }
    c[k] = r;
    j=0;
    for(i=k-1;i>=0;i--){
         mul[j++]=c[i] + 48;
    }
    mul[j]='\0';
    return mul;
}


// Function to calculate factorial
char * factorial(int x){
	static char ans[MAX];
	ans[0] = '1';
	ans[1] = '\0';
	int i,j;
	char* tem;
	
	for(i=1;i<=x;i++){
		char temp[MAX];
		itoa(i,temp,10);
		tem = multiply(ans,temp);
		for(j=0;j<strlen(tem);j++){
			ans[j]=tem[j];
		}
	}
	return ans;
}


int main(){
    int a;
    char *c;
    int la,lb;
    int i=0;
    printf("Enter the number : ");
    scanf("%d",&a);
    printf("Factorial of number is : ");
    c=factorial(a);
    while(c[i]=='0')
    	c++;
    printf("%s",c);
    return 0;
}



Pattern Printing – 39

doubt 19-1

-Firstly we take input of height and width.
– We divide the pattern in 3 parts.
– Topmost row
– Central region
– Bottom row

- For topmost row:

doubt 19-2
– Print numbers from 1 to width (In the below code we have used count variable and initialized it to 0 and increment till width)
– Newline

- For central region:

doubt 19-3
– For each row in this region
– Print the value of count and increment it.
– Now Print spaces (Number of spaces equal to width – 2). Also for each space printed increment the value of count.
– Print the value of count and increment it.
– Newline

- For last row:

doubt 19-4
-Print numbers starting from count and increment it. (Total numbers printed in this row equals width)
– Newline

NOTE: In the below code %3d is used in printf for formatted output.


#include<stdio.h>
int main(){
    int heigth, width,i,j,count=1;
    printf("Enter Height\n");
    scanf("%d",&heigth);

    printf("Enter Width\n");
    scanf("%d",&width);

    // Topmost row
    for(i=0;i<width;i++)
        printf("%3d",count++);

    printf("\n");

    // Central region
    for(i=1;i<heigth-1;i++){
        printf("%3d",count++);
        for(j=1;j<width-1;j++){
            printf("   ");
            count++;
        }
        printf("%3d\n",count++);
    }

    // Bottommost row
    for(i=0;i<width;i++){
        printf("%3d",count++);
    }


    return 0;
}

Pattern Printing – 38

a

- We divide the pattern in 3 parts
– Upper 2 rows(blue)
– Central region(red)
– Bottom 2 rows(purple)

- For upper 2 rows(blue)
b
– Print spaces
– Print stars

- For central region(red)

c

– Print spaces
– Print stars
– Print spaces
– Print stars

- For bottom 2 rows(purple)

d

– Print spaces
– Print stars

#include<stdio.h>
int main(){
	int height, width,i,j;
	
	printf("Enter Height\n");
	scanf("%d",&height);
	
	printf("Enter Width\n");
	scanf("%d",&width);
	
	
	// Upper 2 rows
	for(i=0;i<2;i++){
		for(j=0;j<height-i-1;j++)
			printf(" ");
		for(j=0;j<width;j++)
			printf("*");
		printf("\n");
	}
	
	
	// central region
	for(i=2;i<height-2;i++){
		for(j=0;j<height-i-1;j++)
			printf(" ");
		for(j=0;j<2;j++)
			printf("*");
		for(j=0;j<width-4;j++)
			printf(" ");
		for(j=0;j<2;j++)
			printf("*");
		printf("\n");
	}
	
	
	// bottom 2 rows
	for(i=0;i<2;i++){
		for(j=0;j<1-i;j++)
			printf(" ");
		for(j=0;j<width;j++)
			printf("*");
		printf("\n");
	}
	
	return 0;
}

Roman Numerals

Roman numerals are used frequently to indicate dates, in particular the year (for example, MMXIII represents the year 2013). There are two main differences between roman and arabic numerals.

There is no symbol for zero in roman numerals;
Numeral placement in the roman system can indicate either addition or subtraction.

Roman numeral conversion is specified using the following cases.

I represents 1. Joining two I’s together (i.e. II) represents 2, while III represents 3. However, IIII to represent 4 is forbidden because there is a shorter notation.
V represents 5. Placing I before V (i.e. IV) will mean subtract I from V, i.e. 4. Note that we do not subtract more than one I from V, so IIV to represent 3 is invalid. Placing I after V (i.e. VI) will mean add I to V, i.e. 6. Likewise, VII and VIII represents 7 and 8. To represent 9 and 10, we do not use VIIII and VV respectively because there exist shorter notations.
X represents 10. Following the rule above, IX is 9 while XI is 11.
L represents 50 and works in much the same way as V. So XL is 40 while LX is 60. Additionally, XLI is 41, XLV is 45, XLIV is 44, XLVI is 46, XLIX is 49. Hopefully you get the picture…
C represents 100.
D represents 500.
M represents 1000. M is the last character of the roman numeral system so to represent 9000, there is no choice but to use MMMMMMMMM.

Write a program that reads in a year (> 0), and outputs the year in roman numerals

Sample Runs

The following are sample runs of the program. User input is underlined. Ensure that the last line of output is followed by a newline character.

Sample run #1:

Enter the year : 1
Year 1 in roman numerals is I
Sample run #2:

Enter the year : 2013
Year 2013 in roman numerals is MMXIII

#include<stdio.h>
#include<string.h>

char ans[5];
void getRoman(char ch1, char ch2, char ch3, int n){
	
	
	
	switch(n){
		case 0:
			ans[0] = '\0';
			break;
		case 1:
			ans[0]=ch1;
			ans[1] = '\0';
			break;
		case 2:
			ans[0]=ch1;
			ans[1]=ch1;
			ans[2] = '\0';
			break;
		case 3:
			ans[0]=ch1;
			ans[1]=ch1;
			ans[2]=ch1;
			ans[3] = '\0';
			break;
		case 4:
			ans[0]=ch1;
			ans[1]=ch2;
			ans[2] = '\0';
			break;
		case 5:
			ans[0]=ch2;
			ans[1] = '\0';
			break;
		case 6:
			ans[0]=ch2;
			ans[1]=ch1;
			ans[2] = '\0';
			break;
		case 7:
			ans[0]=ch2;
			ans[1]=ch1;
			ans[2]=ch1;
			ans[3] = '\0';
			break;
		case 8:
			ans[0]=ch2;
			ans[1]=ch1;
			ans[2]=ch1;
			ans[3]=ch1;
			ans[4] = '\0';
			break;
		case 9:
			ans[0]=ch1;
			ans[1]=ch3;
			ans[2] = '\0';
			break;
	}
	
} 
	

int main(){
	
	 
	char final_ans[100];
	final_ans[0]='\0';
	int length,i,j,temp,n,year;
	
	printf("Enter the year : ");
	scanf("%d",&year);
	n=year;
	
	if(n>=1000){
		temp=n/1000;
		for(i=0;i<temp;i++){
			final_ans[i] = 'M';
		}
		final_ans[i] = '\0';
		n%=1000;
	}
		
	if(n>=100){
		temp = n/100;
		getRoman('C','D','M',temp);
		length = strlen(final_ans);
		for(i=0;i<strlen(ans);i++){
			final_ans[length+i]=ans[i];
		}
		final_ans[i+length] = '\0';
		n%=100;
	}
	
	if(n>=10){
		temp = n/10;
		getRoman('X','L','C',temp);
		length = strlen(final_ans);
		for(i=0;i<strlen(ans);i++){
			final_ans[length+i]=ans[i];
		}
		final_ans[i+length]='\0';
		n%=10;
	}
	
	if(n>0){
		
		getRoman('I','V','X',n);
		length = strlen(final_ans);
		for(i=0;i<strlen(ans);i++){
			final_ans[length+i]=ans[i];
		}
		final_ans[i+length]='\0';
	}
	
	printf("Year %d in roman numerals is %s",year,final_ans);
		
	return 0;
}

Explaination of logic for year 2151 -> MMCLI:

– If number(n) is greater than 1000
-Divide the number by 1000 and print that many ‘M’ . (ans= ‘MM’)
– Now calculate the new number by modulo 1000 (n = n%1000)
– If number is greater than 100 call function getRoman(‘C’,’D’,’M’,n/100);
– Append the value retured to ans . (ans = ‘MMC’)
– Now calculate the new number by modulo 100 (n = n%100)
– If number is greater than 10 call function getRoman(‘X’,’L’,’C’,n/10);
– Append the value retured to ans . (ans = ‘MMCL’)
– Now calculate the new number by modulo 10 (n = n%10)
– If number is greater than 0 call function getRoman(‘I’,’V’,’X’,n);
– Append the value retured to ans . (ans = ‘MMCLI’)
– Print final ans.

Pattern Printing – 37

We The Computer Guys Pattern Printing

Write a program tho print this pattern.

This pattern has two parts to print:

  1. Spaces
  2. Numbers

To print this pattern we print the spaces first followed by numbers.

The first inner loop prints spaces and second prints the numbers

#include<stdio.h>
int main()
{
    int n, i, j , k;
    printf("Enter the number of rows\n");
    scanf("%d", &n);  //Input for number of rows
    for (i = 1; i <= n; i++)
    {
    	//Loop for printing spaces
    	for(k=n-i;k>0;k--){
    		//Prints space
    		printf(" ");
    		
    	}
    	
        //loop for each row
        for (j = 1; j <= i; j++)
        {
            //In each row number of elements equal to row number
            printf("%d", j); //Printing elements in a particular row
        }
        //Move to next line
        printf("\n");
    }

    return 0;
}

Find average of n numbers

Write a program to find average of n numbers given by user.

Logic

  1. Take n from user
  2. Take n numbers form user
  3. Compute average and print it
#include<stdio.h>

int main(){
	
	int n,number,sum; 
	//Initilize sum to zero
	sum=0;
	
	printf("How many integers do you wish to average?\n");
	scanf("%d",&n);
	
	int i;
	for(i=1;i<=n;i++){
		
		//Input the number
		scanf("%d",&number);
		
		//Add it to sum
		sum+=number;
			
	}
	
	double avg=(double)sum/n;	//Typecast it to double 
							//coz average can be floating point number
	
	printf("The average of %d numbers is %lf \n",n,avg); // ld --(for)--> double
	
	return 0;
}
 

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

Previous: Pattern Printing 35
Category: Pattern Printing

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

Next Post: Pattern Printing 36
Category: Pattern Printing
Previous Post: Pattern Printing 34

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

Next Post: Pattern Printing 35
Category: Printing Pattern
Previous Post: Pattern Printing 33

Follow

Get every new post delivered to your Inbox.

Join 32 other followers