GoogleTag

Google Search

Showing posts with label CProgramming. Show all posts
Showing posts with label CProgramming. Show all posts

[Programming] Question 33: Write a Program to return the nth row of Pascal's triangle

 

#include <stdio.h>

int binomialCoeff(int n, int k) {
	int res = 1;
	if (k > n - k)
		k = n - k;
	for (int i = 0; i < k; ++i) {
		res *= (n - i);
		res /= (i + 1);
	}
	return res;
}

int main() {
	int n;

	printf("Enter the row number: ");
	scanf("%d", &n);

	for (int i = 0; i < n; ++i) {
		printf("%d ", binomialCoeff(n - 1, i));
	}

	return 0;
} 
 Inside the binomialCoeff function:

- This function calculates the binomial coefficient C(n, k) using the formula C(n, k) = n! / (k! * (n - k)!).

- Inside the main function:

 - The user is prompted to enter the row number.

- A for loop iterates from 0 to n - 1, and in each iteration, it prints the binomial coefficient for that row.

 

[Programming] Question 32: Write a program to form Pascal Triangle using numbers

 

#include <stdio.h>

int main() {
	int rows, coef = 1, space, i, j;

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

	for (i = 0; i < rows; i++) {
		for (space = 1; space <= rows - i; space++)
			printf("  ");

		for (j = 0; j <= i; j++) {
			if (j == 0 || i == 0)
				coef = 1;
			else
				coef = coef * (i - j + 1) / j;
			printf("%4d", coef);
		}
		printf("\n");
	}

	return 0;
} 
Inside the main() function:

- Integer variables `rows`, `coef`, `space`, `i`, and `j` are declared to store the number of rows, coefficients, spaces, and loop iterators.

- The user is prompted to enter the number of rows.

- Two nested loops are used to print the Pascal's triangle.

- The first loop iterates through each row.

- The second loop calculates and prints the coefficients for each row using binomial coefficients.

- The program prints a newline after each row.

 

[Programming] Question 31: Write a Program to create a pyramid pattern using C

 

#include <stdio.h>

int main() {
	int rows, space, i, j;

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

	for (i = 1; i <= rows; ++i) {
		for (space = 1; space <= rows - i; ++space)
			printf("  ");

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

		printf("\n");
	}

	return 0;
} 
Inside the main() function:

- Integer variables `rows`, `space`, `i`, and `j` are declared to store the number of rows, spaces, and loop iterators.

- The user is prompted to enter the number of rows.

- Two nested loops are used to print the pyramid pattern.

- The first loop iterates through each row.

- The second loop prints spaces before the stars for each row.

- Another loop prints the stars for each row.

- The program prints a newline after each row.

 

Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts