如何用C、C++和Python写一个程序来打印图案

261 阅读1分钟

问题说明

我们需要用C、C++和Python编写一个脚本,以便根据用户输入的字母打印出以下模式的字母。

输入

字母 = F

输出

A
AB
ABC
ABCD
ABCDE
ABCDEF

算法

  • 要求用户输入图案的高度h ,范围是1到26(A到Z)。
  • 从范围1 to h ,创建一个外循环i
  • 在外循环内创建一个嵌套的内循环j ,范围从1 to i
  • 在内循环中,我们将使用ASCII码打印一系列的字母。
  • 大写字母的ASCII代码从65开始。

打印一连串字母的C程序

#include <stdio.h>
int main()
{
	int h, i, j;
	char letter;
	//ask user to input the height of the pattern
	printf("Enter the height of pattern(1-26): ");
	scanf("%d", &h);
	
	for(i=1;i<=h;i++)
	{
		for(j=1;j<=i;j++)
		{
			//convert the integer ASCII code
			//to equivalent character value
			letter = j+64;
		
			printf("%c",letter);
		}
		
		//print a new line after every row of alphabet series
		printf("\n");
	}

    return 0;
}

输出

Enter the height of pattern(1-26): 5
A
AB
ABC
ABCD
ABCDE

C++程序打印一连串的英文字母

#include <ioistream>
using namespace std;

int main()
{
	int h, i, j;
	char letter;
	//ask user to input the height of the pattern
	cout<<"Enter the height of pattern(1-26): "; cin>>h;
	
	for(i=1;i<=h;i++)
	{
		for(j=1;j<=i;j++)
		{
			//convert the integer ASCII code
			//to equivalent character value
			letter = j+64;
		
			cout<<letter;
		}
		
		//print a new line after every row of alphabet series
		cout<<endl;
	}
    return 0;
}

输出

Enter the height of pattern(1-26): 6
A
AB
ABC
ABCD
ABCDE
ABCDEF

Python程序打印一连串的字母。

#ask user to input the height of the pattern
h = int(input("Enter the height of pattern(1-26): "))

#outer loop
for i in range(1,h+1):

    for j in range(1, i+1):
        # convert the integer ASCII code
        # to equivalent character value
        letter = chr(64+j)
        print(letter, end="")

    #print a new line after every row of alphabet series
    print()

输出

Enter the height of pattern(1-26): 8
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH

复杂度分析

  • 时间复杂度: O(N2), 在这个程序中,我们使用了一个嵌套的循环,这使得时间复杂性为二次。
  • 空间复杂度:O(1), 程序中没有额外的空间使用,所以空间复杂度是不变的。