Given the total number of rows as n, the task is to print the given pattern.
*
1*
*2*
1*3*
*2*4*
1*3*5*
*2*4*6*
1*3*5*7*
*2*4*6*8*
1*3*5*7*9*
.
.
Examples:
Input: n = 5
Output:
*
1*
*2*
1*3*
*2*4*
Input: n = 10
Output:
*
1*
*2*
1*3*
*2*4*
1*3*5*
*2*4*6*
1*3*5*7*
*2*4*6*8*
1*3*5*7*9*
Below is the solution to the above problem:
C++
#include <iostream>
using namespace std;
void Pattern( int n)
{
int i, j, k;
for (i = 1; i <= n; i++) {
for (j = 1, k = i; j <= i; j++, k--) {
if (k % 2 == 0) {
cout << j;
}
else {
cout << "*" ;
}
}
cout << "\n" ;
}
}
int main()
{
int n = 5;
Pattern(n);
return 0;
}
|
C
#include <stdio.h>
void Pattern( int n)
{
int i, j, k;
for (i = 1; i <= n; i++) {
for (j = 1, k = i; j <= i; j++, k--) {
if (k % 2 == 0) {
printf ( "%d" , j);
}
else {
printf ( "*" );
}
}
printf ( "\n" );
}
}
int main()
{
int n = 5;
Pattern(n);
return 0;
}
|
Java
import java.util.Scanner;
class Pattern {
static void display( int n)
{
int i, j, k;
for (i = 1 ; i <= n; i++) {
for (j = 1 , k = i; j <= i; j++, k--) {
if (k % 2 == 0 ) {
System.out.print(j);
}
else {
System.out.print( "*" );
}
}
System.out.print( "\n" );
}
}
public static void main(String[] args)
{
int n = 5 ;
display(n);
}
}
|
Python3
def display(n):
for i in range ( 1 , n + 1 ):
k = i
for j in range ( 1 , i + 1 ):
if k % 2 = = 0 :
print (j, end = '')
else :
print ( '*' , end = '')
k - = 1
print ()
n = 5
display(n)
|
C#
using System;
class GFG
{
static void display( int n)
{
int i, j, k;
for (i = 1; i <= n; i++)
{
for (j = 1, k = i; j <= i; j++, k--)
{
if (k % 2 == 0)
{
Console.Write(j);
}
else
{
Console.Write( "*" );
}
}
Console.Write( "\n" );
}
}
public static void Main()
{
int n = 5;
display(n);
}
}
|
PHP
<?php
function display( $n )
{
$i ;
$j ;
$k ;
for ( $i =1; $i <= $n ; $i ++)
{
for ( $j =1, $k = $i ; $j <= $i ; $j ++, $k --)
{
if ( $k %2==0){
echo $j ;
}
else {
echo "*" ;
}
}
echo "\n" ;
}
}
$n = 5;
display( $n );
?>
|
Javascript
<script>
function Pattern(n)
{
var i, j, k;
for (i = 1; i <= n; i++) {
for (j = 1, k = i; j <= i; j++, k--) {
if (k % 2 == 0) {
document.write( j);
}
else {
document.write( "*" );
}
}
document.write( "<br>" );
}
}
var n = 5;
Pattern(n);
</script>
|
Output
*
1*
*2*
1*3*
*2*4*
Complexity Analysis:
- Time Complexity: O(n2), where n represents the given input.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!