1) Write a program to print following Pyramid
Code:
#include <stdio.h>
int main()
{
int n, c, k, s= 1;
printf("Enter number of rows\n");
scanf("%d", &n);
s = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= s; c++)
printf(" ");
s--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("\n");
}
s = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= s; c++)
printf(" ");
s++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");
printf("\n");
}
return 0;
}
OUTPUT:
2) Hollow Square Pattern with Diagonal
CODE:
#include <stdio.h>
int main()
{
int i, j, N;
printf("Enter number of rows: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
for(j=1; j<=N; j++)
{
if(i==1 || i==N || j==1 || j==N || i==j || j==(N - i + 1))
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
OUTPUT:
3) Pascal’s Triangle Program
CODE:
#include <stdio.h>
int main()
{
int rows, coef = 1, space, i, j;
printf("Enter the 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;
}
OUTPUT:
4)Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.
Code:
def rotate_array(arr, d, n):
d=d%n
arr_out = [0] * n
for i in range(n):
val = (i + d) % n
arr_out[val] = arr[i]
return arr_out
Output:
5) Given an unsorted array of integers, find the pair with given sum in it.
Code:
def pair_sum(arr, sum_val):
values = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == sum_val:
values.append([i, j])
return values
OUTPUT:
6) Given a array of integers, find the maximum product of two integers in an array.
Code:
def max_product(arr):
max_product_val = 0
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] * arr[j] > max_product_val:
max_product_val = arr[i] * arr[j]
return max_product_val
Output:
7) Given a array of range n, with elements 1 to n-1 and one element repeating, find the
duplicate element.
Code:
def duplicate_element(arr):
arr_sorted = sorted(arr)
duplicate = -1
for i in range(len(arr_sorted)-1):
if arr_sorted[i] == arr_sorted[i+1]:
duplicate = arr_sorted[i]
break
return duplicate
Output:
8) Given an array of integers, move all zeros present in the array to the end, keeping the
relative order of the elements in the array intact.
Code:
def move_zero(arr):
arr_out = []
n_zero = 0
for element in arr:
if element != 0:
arr_out.append(element)
else:
n_zero += 1
for i in range(n_zero):
arr_out.append(0)
return arr_out
Output: