SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:17 | ISBN:978013274719 | Edition: 6

Question

(Display the ASCII character table) Write a program that displays the characters in the ASCII character table from ! to ~. Display ten characters per line. The characters are separated by exactly one space.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program code:

# Define the starting and ending ASCII values for the characters
start = ord('!')  # ASCII value of '!'
end = ord('~')  # ASCII value of '~'

# Initialize a counter to keep track of the number of characters displayed
count = 0

# Iterate over the ASCII range from start to end (inclusive)
for ascii_value in range(start, end + 1):
    # Convert the ASCII value back to a character
    character = chr(ascii_value)

    # Print the character with a space, end=' ' ensures they are separated by exactly one space
    print(character, end=' ')

    # Increment the count
    count += 1

    # Check if ten characters have been displayed
    if count % 10 == 0:
        print()  # Print a new line after every ten characters

# Print a new line if the last line doesn't have ten characters
if count % 10 != 0:
    print()

Executed Output:

   
! " # $ % & ' ( ) * 
+ , - . / 0 1 2 3 4 
5 6 7 8 9 : ; < = > 
? @ A B C D E F G H 
I J K L M N O P Q R 
S T U V W X Y Z [ \ 
] ^ _ ` a b c d e f 
g h i j k l m n o p 
q r s t u v w x y z 
{ | } ~ 

 

0 0

Discussions

Post the discussion to improve the above solution.