Python Program to Check If a Line Touches or Intersects a Circle

Program to Check If a Line Touches or Intersects a Circle

In the previous article, we have discussed Python Program for Pizza Cut Problem (Or Circle Division by Lines)
Given the coordinates of the center point as (0,0), the radius of the circle, and the equation of a line and the task is to check whether the given line touches or intersects the circle.

The line equation is in the form ax+by+c.

Hence a, b, c values are given for a line equation.

The three possibilities :

  • The Line intersect the circle
  • The Line touches the circle
  • The Line outside the circle

The following formula can be used to calculate the distance of a line from a point:

(ax+by+c)/sqrt(a*a+b*b)

If d > r,  the line lies outside the circle.
If d = r,  the line touches the circle.
If d < r,  the line intersects the circle.

where d = the distance of a line from a center.

r is the radius of the circle.

Examples:

Example1:

Input:

Given radius = 6
Given  a = 2
Given  b = 1
Given  c = 1

Output:

The Given line intersects the circle

Example2:

Input:

Given radius = 5
Given a = 1
Given b = 1
Given c = -15

Output:

The Given line is outside the circle

Program to Check If a Line Touches or Intersects a Circle in Python

Below are the ways to check whether the given line touches or intersects the circle in Python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the radius as static input and store it in a variable.
  • Take the x-coordinate of the center and initialize its value to 0.
  • Take the y-coordinate of the center and initialize its value to 0.
  • Give the number as static input and store it in a variable.
  • Give the other number as static input and store it in another variable.
  • Give the third number as static input and store it in another variable.
  • Calculate the distance of the given line from the given center point using the above given mathematical formula, abs(), math.sqrt() functions.
  • Store it in another variable.
  • Check if the given radius value is equal to the above-obtained distance using the if conditional statement.
  • If it is true, then print “The Given line touches the circle”.
  • Check if the given radius value is greater than the above-obtained distance using the elif conditional statement.
  • If it is true, then print “The Given line intersects the circle”.
  • Else, print “The Given line is outside the circle”.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the radius as static input and store it in a variable.
gvn_radiuss = 6
# Take the x-coordinate of center and initialize its value to 0.
m = 0
# Take the y-coordinate of center and initialize its value to 0.
n = 0
# Give the number as static input and store it in a variable.
p = 2
# Give the other number as static input and store it in another variable.
q = 1
# Give the third number as static input and store it in another variable.
r = 1
# Calculate the distance of the given line from the given center point using the
# above given mathematical formula, abs(), math.sqrt() functions
# store it in another variable.
distancee_val = ((abs(p * m + q * n + r)) /
                 math.sqrt(p * p + q * q))
# Check if the given radius value is equal to the above obtained distance using the
# if conditional statement.
if (gvn_radiuss == distancee_val):
    # If it is true, then print "The Given line touches the circle".
    print("The Given line touches the circle")
# Check if the given radius value is greater than the above obtained distance using
# the elif conditional statement.
elif (gvn_radiuss > distancee_val):
    # If it is true, then print "The Given line intersects the circle".
    print("The Given line intersects the circle")
else:
    # Else, print "The Given line is outside the circle".
    print("The Given line is outside the circle")

Output:

The Given line intersects the circle

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the radius as user input using the int(input()) function and store it in a variable.
  • Take the x-coordinate of the center and initialize its value to 0.
  • Take the y-coordinate of the center and initialize its value to 0.
  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the other number as user input using the int(input()) function and store it in another variable.
  • Give the third number as user input using the int(input()) function and store it in another variable.
  • Calculate the distance of the given line from the given center point using the above given mathematical formula, abs(), math.sqrt() functions.
  • Store it in another variable.
  • Check if the given radius value is equal to the above-obtained distance using the if conditional statement.
  • If it is true, then print “The Given line touches the circle”.
  • Check if the given radius value is greater than the above-obtained distance using the elif conditional statement.
  • If it is true, then print “The Given line intersects the circle”.
  • Else, print “The Given line is outside the circle”.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the radius as user input using the int(input()) function and 
# store it in a variable.
gvn_radiuss = int(input("Enter some random number = "))
# Take the x-coordinate of center and initialize its value to 0.
m = 0
# Take the y-coordinate of center and initialize its value to 0.
n = 0
# Give the number as user input using the int(input()) function and store it in a variable.
p = int(input("Enter some random number = "))
# Give the other number as user input using the int(input()) function and store it in another variable.
q = int(input("Enter some random number = "))
# Give the third number as user input using the int(input()) function and store it in another variable.
r = int(input("Enter some random number = "))
# Calculate the distance of the given line from the given center point using the
# above given mathematical formula, abs(), math.sqrt() functions
# store it in another variable.
distancee_val = ((abs(p * m + q * n + r)) /
                 math.sqrt(p * p + q * q))
# Check if the given radius value is equal to the above obtained distance using the
# if conditional statement.
if (gvn_radiuss == distancee_val):
    # If it is true, then print "The Given line touches the circle".
    print("The Given line touches the circle")
# Check if the given radius value is greater than the above obtained distance using
# the elif conditional statement.
elif (gvn_radiuss > distancee_val):
    # If it is true, then print "The Given line intersects the circle".
    print("The Given line intersects the circle")
else:
    # Else, print "The Given line is outside the circle".
    print("The Given line is outside the circle")

Output:

Enter some random number = 5
Enter some random number = 1
Enter some random number = 1
Enter some random number = -15
The Given line is outside the circle

Enhance your coding skills with our list of Python Basic Programs provided and become a pro in the general-purpose programming language Python in no time.

Python Program for Pizza Cut Problem (Or Circle Division by Lines)

Program for Pizza Cut Problem (Or Circle Division by Lines)

In the previous article, we have discussed Python Program to Check Whether Triangle is Valid or Not if Sides are Given
Given the number of cuts and the task is to get the maximum number of pieces from the given number of cuts in python.

Formula:

1 + n*(n+1)/2

where n= number of cuts.

Examples:

Example1:

Input:

Given number of cuts = 4

Output:

The maximum number of pieces from the given number of cuts =  11

Example2:

Input:

Given number of cuts = 5

Output:

The maximum number of pieces from the given number of cuts =  16

Program for Pizza Cut Problem (Or Circle Division by Lines) in Python

Below are the ways to get the maximum number of pieces from the given number of cuts in python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the number of cuts as static input and store it in a variable.
  • Create a function to say Get_Max_Pieces() which takes the given number of cuts as an argument, and returns the maximum number of pieces from the given number of cuts.
  • Inside the function, calculate the maximum number of pieces by using the above given mathematical formula and convert it to an integer using the int() function.
  • Store it in another variable.
  • Return the above result.
  • Pass the given number of cuts as an argument to the Get_Max_Pieces() function and store it in another variable.
  • Print the above result which is the maximum number of pieces from the given number of cuts.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Get_Max_Pieces() which takes the given number of cuts as
# an argument, and returns the maximum number of pieces from the given number of cuts.


def Get_Max_Pieces(no_of_cuts):
    # Inside the function, calculate the maximum number of pieces by using the above
        # given mathematical formula and convert it to an integer using the int() function.
        # Store it in another variable.
    k = int(1 + no_of_cuts * (no_of_cuts + 1) / 2)
    # Return the above result.
    return k


# Give the number of cuts as static input and store it in a variable.
no_of_cuts = 4
# Pass the given number of cuts as an argument to the Get_Max_Pieces() function
# and store it in another variable.
maxim_pieces = Get_Max_Pieces(no_of_cuts)
# Print the above result which is the maximum number of pieces from the given
# number of cuts.
print("The maximum number of pieces from the given number of cuts = ", maxim_pieces)

Output:

The maximum number of pieces from the given number of cuts =  11

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the number of cuts as user input using the int(input()) function and store it in a variable.
  • Create a function to say Get_Max_Pieces() which takes the given number of cuts as an argument, and returns the maximum number of pieces from the given number of cuts.
  • Inside the function, calculate the maximum number of pieces by using the above given mathematical formula and convert it to an integer using the int() function.
  • Store it in another variable.
  • Return the above result.
  • Pass the given number of cuts as an argument to the Get_Max_Pieces() function and store it in another variable.
  • Print the above result which is the maximum number of pieces from the given number of cuts.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Get_Max_Pieces() which takes the given number of cuts as
# an argument, and returns the maximum number of pieces from the given number of cuts.


def Get_Max_Pieces(no_of_cuts):
    # Inside the function, calculate the maximum number of pieces by using the above
        # given mathematical formula and convert it to an integer using the int() function.
        # Store it in another variable.
    k = int(1 + no_of_cuts * (no_of_cuts + 1) / 2)
    # Return the above result.
    return k


# Give the number of cuts as user input using the int(input()) function 
# and store it in a variable.
no_of_cuts = int(input("Enter some random number = "))
# Pass the given number of cuts as an argument to the Get_Max_Pieces() function
# and store it in another variable.
maxim_pieces = Get_Max_Pieces(no_of_cuts)
# Print the above result which is the maximum number of pieces from the given
# number of cuts.
print("The maximum number of pieces from the given number of cuts = ", maxim_pieces)

Output:

Enter some random number = 5
The maximum number of pieces from the given number of cuts = 16

Dive into numerous Python Programming Language Examples for practice and get the best out of the tutorial and learn python one step at a time.

Python Program to Print Reverse Pyramid of Numbers

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Given the number of rows of the pyramid, the task is to print a Reverse Pyramid of Numbers in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 10

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

Example2:

Input:

Given number of rows = 6

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

Program to Print Reverse Pyramid of Numbers in C,C++, and Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from the parent loop iterator value to 0 in decreasing order using another For loop(Nested For Loop).
  • Print the iterator value of the inner for loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numbrrows = 10
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows):
    # Loop from the parent loop iterator value to 0 in decreasing order
    # using another For loop(Nested For Loop).
    for n in range(m, 0, -1):
        # Print the iterator value of the inner for loop.
        print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 10;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 10;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from the parent loop iterator value to 0 in decreasing order using another For loop(Nested For Loop).
  • Print the iterator value of the inner for loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numbrrows = int(input('Enter some random number of rows = '))
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows):
    # Loop from the parent loop iterator value to 0 in decreasing order
    # using another For loop(Nested For Loop).
    for n in range(m, 0, -1):
        # Print the iterator value of the inner for loop.
        print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

2) C++ Implementation

Give the number of rows as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as user input using
    // cin and store it in a variable.
    int numbrrows;
    cin >> numbrrows;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

3) C Implementation

Give the number of rows as user input using scanf and store it in a variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numbrrows;
    scanf("%d", &numbrrows);
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

Related Programs:

Python Program to Print Inverted Right Triangle of Numbers

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Given the number of rows of the Triangle, the task is to Print an Inverted Right Triangle of Numbers in C, C++, and Python

Examples:

Example1:

Input:

given number of rows of the Inverted Right Triangle Pattern =13

Output:

13 13 13 13 13 13 13 13 13 13 13 13 13 
12 12 12 12 12 12 12 12 12 12 12 12 
11 11 11 11 11 11 11 11 11 11 11 
10 10 10 10 10 10 10 10 10 10 
9 9 9 9 9 9 9 9 9 
8 8 8 8 8 8 8 8 
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1

Example2:

Input:

given number of rows of the Inverted Right Triangle Pattern =8

Output:

8 8 8 8 8 8 8 8 
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1

Program to Print an Inverted Right Triangle of Numbers in C, C++, and Python

Below are the ways to Print an Inverted Right Triangle of Numbers in C, C++, and Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows of the Inverted Right Triangle as static input and store it in a variable.
  • Loop from the given number of rows to 0 using For loop and take iterator value as m.
  • Loop till the iterator value of the first loop using another nested For loop.
  • Print the First Loop iterator value that is m and space character.
  • Print the newline character after inner for loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows of the Inverted Right Triangle as static input and store it in a variable.
triNumRows = 13
# Loop from the given number of rows to 0 using For loop and take iterator value as m.
for m in range(triNumRows, -1, -1):
    # Loop till the iterator value of the first loop using another nested For loop.
    for n in range(m):
        # Print the First Loop iterator value that is m and space character.
        print(m, end=' ')
    # Print the newline character after inner for loop.
    print()

Output:

13 13 13 13 13 13 13 13 13 13 13 13 13 
12 12 12 12 12 12 12 12 12 12 12 12 
11 11 11 11 11 11 11 11 11 11 11 
10 10 10 10 10 10 10 10 10 10 
9 9 9 9 9 9 9 9 9 
8 8 8 8 8 8 8 8 
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1 

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows of the Inverted Right
    // Triangle as static input and store it in a variable.
    int triNumRows = 8;
    // Loop from the given number of rows to 0 using For
    // loop and take iterator value as m.
    for (int m = triNumRows; m >= 0; m--) {

        // Loop till the iterator value of the first loop
        // using another nested For loop.
        for (int n = 0; n < m; n++) {
            // Print the First Loop iterator value that is m
            // and space character.
            cout << m << " ";
        }
        // Print the newline character after inner for loop.
        cout << endl;
    }

    return 0;
}

Output:

8 8 8 8 8 8 8 8 
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1 

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows of the Inverted Right
    // Triangle as static input and store it in a variable.
    int triNumRows = 8;
    // Loop from the given number of rows to 0 using For
    // loop and take iterator value as m.
    for (int m = triNumRows; m >= 0; m--) {

        // Loop till the iterator value of the first loop
        // using another nested For loop.
        for (int n = 0; n < m; n++) {
            // Print the First Loop iterator value that is m
            // and space character.
            printf("%d ", m);
        }
        // Print the newline character after inner for loop.
        printf("\n");
    }
    return 0;
}

Output:

8 8 8 8 8 8 8 8 
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1 

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows of the Inverted Right Triangle as user input and store it in a variable.
  • Loop from the given number of rows to 0 using For loop and take iterator value as m.
  • Loop till the iterator value of the first loop using another nested For loop.
  • Print the First Loop iterator value that is m and space character.
  • Print the newline character after inner for loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows of the Inverted Right Triangle as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows of the Inverted Right Triangle as user input using int(input()) and store it in a variable.
triNumRows = int(input(
    'Enter some random number of rows of the Inverted Right Triangle Pattern = '))
# Loop from the given number of rows to 0 using For loop and take iterator value as m.
for m in range(triNumRows, -1, -1):
    # Loop till the iterator value of the first loop using another nested For loop.
    for n in range(m):
        # Print the First Loop iterator value that is m and space character.
        print(m, end=' ')
    # Print the newline character after inner for loop.
    print()

Output:

Enter some random number of rows of the Inverted Right Triangle Pattern = 7
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1

2) C++ Implementation

Give the number of rows of the Inverted Right Triangle as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows of the Inverted Right
    // Triangle as user input using cin and store it in a
    // variable.
    int triNumRows;
    cout << "Enter some random number of rows of the "
            "Inverted Right Triangle Pattern = "
         << endl;
    cin >> triNumRows;
    // Loop from the given number of rows to 0 using For
    // loop and take iterator value as m.
    for (int m = triNumRows; m >= 0; m--) {

        // Loop till the iterator value of the first loop
        // using another nested For loop.
        for (int n = 0; n < m; n++) {
            // Print the First Loop iterator value that is m
            // and space character.
            cout << m << " ";
        }
        // Print the newline character after inner for loop.
        cout << endl;
    }

    return 0;
}

Output:

Enter some random number of rows of the Inverted Right Triangle Pattern = 
6
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1

3) C Implementation

Give the number of rows of the Inverted Right Triangle as user input using scanf and store it in a variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows of the Inverted Right
    // Triangle as user input using scanf and store it in a
    // variable.
    int triNumRows;
    scanf("%d", &triNumRows);
    // Loop from the given number of rows to 0 using For
    // loop and take iterator value as m.
    for (int m = triNumRows; m >= 0; m--) {

        // Loop till the iterator value of the first loop
        // using another nested For loop.
        for (int n = 0; n < m; n++) {
            // Print the First Loop iterator value that is m
            // and space character.
            printf("%d ", m);
        }
        // Print the newline character after inner for loop.
        printf("\n");
    }
    return 0;
}

Output:

15
15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 
14 14 14 14 14 14 14 14 14 14 14 14 14 14 
13 13 13 13 13 13 13 13 13 13 13 13 13 
12 12 12 12 12 12 12 12 12 12 12 12 
11 11 11 11 11 11 11 11 11 11 11 
10 10 10 10 10 10 10 10 10 10 
9 9 9 9 9 9 9 9 9 
8 8 8 8 8 8 8 8 
7 7 7 7 7 7 7 
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1

Related Programs:

Python Program to Print 1 and 0 in Alternative Columns

Python Program to Print 1 and 0 in Alternative Columns

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Given the number of rows and columns, the task is to print 1 and 0 in alternative columns in C, C++, and Python.

Examples:

Example1:

Input:

given number of rows =4
given number of columns=3

Output:

1 0 1 
1 0 1 
1 0 1 
1 0 1

Example2:

Input:

given number of rows =7
given number of columns=15

Output:

1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

Program to Print 1 and 0 in alternative Columns in C, C++, and Python

Below are the ways to print 1 and 0 in alternative columns in C, C++, and Python.

If you look closely at the pattern, you’ll see that for all odd columns, 1 is printed and for all even columns, 0 is printed.

As a result, before displaying integers inside the inner loop, you must check for even-odd conditions. If the current column is an odd number, print 1, otherwise, print 0.

The following is a step-by-step description of the logic used to print a 1, 0 number pattern at alternate columns.

Method #1: Using For loop

Approach:

  • Give the number of rows and number of columns as static input.
  • Store them in two separate variables row numbers and column numbers.
  • Run an outer loop from 1 to rows to iterate through the rows using For loop.
  • Iterate through the columns from 1 to cols using another For inner loop.
  • Before printing any number, we must first check the condition inside the inner loop.
  • This means that for every odd column, 1 is displayed, and for every even column, 0 is displayed.
  • We check whether the column is odd or not using the if statement.
  • If it is true then print 1 else print 0.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

Python Program to Print 1 and 0 in Alternative Columns

# Give the number of rows and number of columns as static input.
# Store them in two separate variables row numbers and column numbers.
rownumbs = 15
colnumbs = 11
# Run an outer loop from 1 to rows to iterate through the rows using For loop.
for m in range(1, rownumbs+1):
  # Iterate through the columns from 1 to cols using another For inner loop.
    for n in range(1, colnumbs+1):
      # Before printing any number, we must first check the condition inside the inner loop.
      # This means that for every odd column, 1 is displayed, and for every even column, 0 is displayed.
      # We check whether the column is odd or not using the if statement.
        if(n % 2 == 1):
            print('1', end=' ')
        # If it is true then print 1 else print 0.
        else:
            print('0', end=' ')
    print()

Output:

1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1

2) C++ Implementation

It is the same as the python approach but just the change in syntax.

Below is the implementation:

C++ Program to Print 1 and 0 in Alternative Columns

#include <iostream>
using namespace std;

int main()
{
    // Give the number of rows and number of columns as
    // static input.
    // Store them in two separate variables row numbers and
    // column numbers.
    int rownumbs = 15;
    int colnumbs = 11;
    // Run an outer loop from 1 to rows to iterate through
    // the rows using For loop.
    for (int i = 1; i <= rownumbs; i++) {
        // Iterate through the columns from 1 to cols using
        // another For inner loop.
        for (int j = 1; j <= colnumbs;
             j++) { // Before printing any number, we must
                    // first check the condition inside the
                    // inner loop. This means that for every
                    // odd column, 1 is displayed, and for
                    // every even column, 0 is displayed. We
                    // check whether the column is odd or
                    // not using the if statement.
            if (j % 2 == 1)
                cout << "1 ";
            // If it is true then print 1 else print 0.
            else
                cout << "0 ";
        }
        cout << endl;
    }
    return 0;
}

Output:

1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1

3) C implementation

It is the same as the python approach but just the change in syntax.

Below is the implementation:

C Program to Print 1 and 0 in Alternative Columns

#include <stdio.h>

int main(void)
{
    // Give the number of rows and number of columns as
    // static input.
    // Store them in two separate variables row numbers and
    // column numbers.
    int rownumbs = 15;
    int colnumbs = 11;
    // Run an outer loop from 1 to rows to iterate through
    // the rows using For loop.
    for (int i = 1; i <= rownumbs; i++) {
        // Iterate through the columns from 1 to cols using
        // another For inner loop.
        for (int j = 1; j <= colnumbs;
             j++) { // Before printing any number, we must
            // first check the condition inside the
            // inner loop. This means that for every
            // odd column, 1 is displayed, and for
            // every even column, 0 is displayed. We
            // check whether the column is odd or
            // not using the if statement.
            if (j % 2 == 1)
                printf("1 ");
            // If it is true then print 1 else print 0.
            else
                printf("0 ");
        }
        printf("\n");
    }
    return 0;
}

Output:

1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1

Method #2:Using while loop

1) C Implementation

We just iterate till rownumbs and columumbs using a while loop.

Below is the implementation:

Python Program to Print 1 and 0 in Alternative Columns Using While Loop

#include <stdio.h>

int main(void)
{
    // Give the number of rows and number of columns as
    // static input.
    // Store them in two separate variables row numbers and
    // column numbers.
    int rownumbs = 4;
    int colnumbs = 3;
    // Run an outer loop from 1 to rows to iterate through
    // the rows using For loop.
    while (rownumbs > 0) {
        // Iterate through the columns from 1 to cols using
        // another For inner loop.
        int tempcol = 1;
        while (tempcol <= colnumbs) { // Before printing any
                                      // number, we must
            // first check the condition inside the
            // inner loop. This means that for every
            // odd column, 1 is displayed, and for
            // every even column, 0 is displayed. We
            // check whether the column is odd or
            // not using the if statement.
            if (tempcol % 2 == 1)
                printf("1 ");
            // If it is true then print 1 else print 0.
            else
                printf("0 ");
            tempcol++;
        }
        rownumbs--;
        printf("\n");
    }
    return 0;
}

2) C++ Implementation:

We just iterate till rownumbs and columumbs using a while loop.

Below is the implementation:
CPP Program to Print 1 and 0 in Alternative Columns Using While Loop

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows and number of columns as
    // static input.
    // Store them in two separate variables row numbers and
    // column numbers.
    int rownumbs = 13;
    int colnumbs = 20;
    // Run an outer loop from 1 to rows to iterate through
    // the rows using For loop.
    while (rownumbs > 0) {
        // Iterate through the columns from 1 to cols using
        // another For inner loop.
        int tempcol = 1;
        while (tempcol <= colnumbs) { // Before printing any
                                      // number, we must
            // first check the condition inside the
            // inner loop. This means that for every
            // odd column, 1 is displayed, and for
            // every even column, 0 is displayed. We
            // check whether the column is odd or
            // not using the if statement.
            if (tempcol % 2 == 1)
                cout << "1 ";
            // If it is true then print 1 else print 0.
            else
                cout << "0 ";
            tempcol++;
        }
        rownumbs--;
        cout << endl;
    }
    return 0;
}

Output:

1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0

3) Python Implementation

We just iterate till rownumbs and columumbs using a while loop.

Below is the implementation:

Python Program to Print 1 and 0 in Alternative Columns Using While Loop

# Give the number of rows and number of columns as static input.
# Store them in two separate variables row numbers and column numbers.
rownumbs = 6
colnumbs = 11
# Run an outer loop from 1 to rows to iterate through the rows using For loop.
while(rownumbs > 0):
  # Iterate through the columns from 1 to cols using another For inner loop.
    tempcol = 1
    while(tempcol <= colnumbs):
      # Before printing any number, we must first check the condition inside the inner loop.
      # This means that for every odd column, 1 is displayed, and for every even column, 0 is displayed.
      # We check whether the column is odd or not using the if statement.
        if(tempcol % 2 == 1):
            print('1', end=' ')
        # If it is true then print 1 else print 0.
        else:
            print('0', end=' ')
        tempcol += 1
    rownumbs -= 1
    print()

Output:

1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 1 0 1

Related Programs:

Python Program to Print Nth word in a given String

Program to Print Nth word in a given String

In this article, we will look at how to find the Nth word in a given text using Python.
We frequently encounter circumstances in which we do not require the complete string but merely a certain word from it.

Given multiple strings separated by spaces, the task is to print the Nth word in the given string in Python.

Examples:

Example1:

Input:

Given string =Good morning this is btechgeeks platform
Given n=3

Output:

The [ 3 ] th word in the given Good morning this is btechgeeks platform is { this }

Example2:

Input:

Given string =hello thi sis btechgeeks
Given n=4

Output:

The [ 4 ] th word in the given hello thi sis btechgeeks is { btechgeeks }

Program to Print Nth word in a given String in Python

Below are the ways to print the Nth word in the given string in Python.

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Method #1: Using split() Function (Static Input)

Approach:

  • Give the string as static input and store it in the variable.
  • Give the value of n as static input and store it in another variable.
  • Convert this string into a list of words and split them with spaces using split() and list() functions.
  • Print the nth word in the given list by printing the n-1 indexed element in the above list.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in the variable.
gvnwordsstring = 'Good morning this is btechgeeks platform'
# Give the value of n as static input and store it in another variable.
p = 3
# Convert this string into a list of words and
# split them with spaces using split() and list() functions.
stringwordslist = list(gvnwordsstring.split())

# Print the nth word in the given list by printing the n-1 indexed element
# in the above list.
nthword = stringwordslist[p-1]
print('The [', p, '] th word in the given',
      gvnwordsstring, 'is {', nthword, '}')

Output:

The [ 3 ] th word in the given Good morning this is btechgeeks platform is { this }

Method #2: Using split() Function (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Give the value of n as user input using the int(input()) function and store it in another variable.
  • Convert this string into a list of words and split them with spaces using split() and list() functions.
  • Print the nth word in the given list by printing the n-1 indexed element in the above list.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gvnwordsstring = input('Enter some random string = ')
# Give the value of n as user input using the int(input())
# function and store it in another variable.
p = int(input('Enter some random value of n ='))
# Convert this string into a list of words and
# split them with spaces using split() and list() functions.
stringwordslist = list(gvnwordsstring.split())

# Print the nth word in the given list by printing the n-1 indexed element
# in the above list.
nthword = stringwordslist[p-1]
print('The [', p, '] th word in the given',
      gvnwordsstring, 'is {', nthword, '}')

Output:

Enter some random string = hello this is btechgeeks
Enter some random value of n =4
The [ 4 ] th word in the given hello thi sis btechgeeks is { btechgeeks }

Related Programs:

Python Program to Take in a String and Replace Every Blank Space with Hyphen

Program to Take in a String and Replace Every Blank Space with Hyphen

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

given_string='btechgeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string = hello this is BtechGeeks

Output:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

Example2:

Input:

given string = files will be upload to a folder you can read those files in the program folder

Output:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

Program to Take in a String and Replace Every Blank Space with Hyphen

Below are the ways to scan the string and replace every blank space with a hyphen in Python.

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Method #1:Using replace function (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Using the replace function replace all blank space with a hyphen by providing blank space as the first argument and hyphen as the second argument in replace function.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'hello this is BtechGeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

Method #2:Using replace function (User Input)

Approach:

  • Give the string as user input using the int(input()) function and store it in a variable.
  • Using the replace function replace all blank space with a hyphen by providing blank space as the first argument and hyphen as the second argument in replace function.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using int(input()) function and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

The replace() function replaces all instances of ” with ‘-‘.

Python Program to Form a New String where the First Character and the Last Character have been Exchanged

Program to Form a New String where the First Character and the Last Character have been Exchanged

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

given_string='btechgeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string =  hello this is btechgeeks

Output:

The original string before modification = hello this is btechgeeks
The new string after modification = sello this is btechgeekh

Example2:

Input:

given string = this is btechgeeks online coding platform for geeks

Output:

Enter some random string = this is btechgeeks online coding platform for geeks
The original string before modification = this is btechgeeks online coding platform for geeks
The new string after modification = shis is btechgeeks online coding platform for geekt

Program to Form a New String where the First Character and the Last Character have been Exchanged

Below are the ways to form a new string in which the first and last characters have been swapped

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

1)Using slicing(static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a function that swaps the first and last character of the string.
  • Pass the given string as an argument to the function.
  • Split the string in the function.
  • The last character is then added to the middle half of the string, which is then added to the first character.
  • The modified string will be returned.
  • Print the modified string
  • The Exit of the program.

Below is the implementation :

# Take a function that swaps the first and last character of the string.
def swapString(given_string):
    # Split the string in the function.
    # The last character is then added to the middle half of the string,
    # which is then added to the first character.
    modifiedstring = given_string[-1:] + given_string[1:-1] + given_string[:1]
    # The modified string will be returned.
    return modifiedstring


# Give the string as static input and store it in a variable.
given_string = 'hello this is btechgeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Pass the given string as an argument to the function.
modified_string = swapString(given_string)
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

The original string before modification = hello this is btechgeeks
The new string after modification = sello this is btechgeekh

Explanation:

  • Give the string as static input and store it in a variable.
  • This string is supplied to a function as an argument.
  • Using string slicing, the string is split into three parts in the function: the last character, the middle part, and the first character.
  • The ‘+’ operator is then used to concatenate these three parts.
  • After that, the modified string is printed.

2)Using slicing(User input)

Approach:

  • Give the string as user input using int(input()) and store it in a variable.
  • Take a function that swaps the first and last character of the string.
  • Pass the given string as an argument to the function.
  • Split the string in the function.
  • The last character is then added to the middle half of the string, which is then added to the first character.
  • The modified string will be returned.
  • Print the modified string
  • The Exit of the program.

Below is the implementation :

# Take a function that swaps the first and last character of the string.
def swapString(given_string):
    # Split the string in the function.
    # The last character is then added to the middle half of the string,
    # which is then added to the first character.
    modifiedstring = given_string[-1:] + given_string[1:-1] + given_string[:1]
    # The modified string will be returned.
    return modifiedstring


# Give the string as user input using int(input()) and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Pass the given string as an argument to the function.
modified_string = swapString(given_string)
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

Enter some random string = this is btechgeeks online coding platform for geeks
The original string before modification = this is btechgeeks online coding platform for geeks
The new string after modification = shis is btechgeeks online coding platform for geekt

Related Programs:

Python Program to Implement the Latin Alphabet Cipher

Python Program to Implement the Latin Alphabet Cipher

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

We will learn how to use Python to implement the Latin Alphabet Cipher.

The Latin Alphabet Cipher Encryption Technique is one of the quickest and most straightforward methods of encoding data. It’s essentially a replacement cipher method, in which each letter of a given input is replaced by its matching number as represented alphabetically.

Examples:

Example1:

Input:

Given string =Hello this is BTechGeeks

Output:

The encrypted message of the given string{ Hello this is BTechGeeks }is :
8 5 12 12 15  
20 8 9 19  
9 19  
2 20 5 3 8 7 5 5 11 19

Example2:

Input:

Given string = btechgeeks python

Output:

The encrypted message of the given string{ btechgeeks python }is :
2 20 5 3 8 7 5 5 11 19 
16 25 20 8 15 14

Python Program to Implement the Latin Alphabet Cipher in Python

Below are the ways to implement the Latin Alphabet Cipher in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input(which consists of only alphabets and spaces) and store it in a variable
  • Iterate through the characters of the string using For loop.
  • We can calculate the ASCII value of the character using the ord() function.
  • Now, transform each input string character to its ASCII value and subtract it from the ASCII value of alphabet A for uppercase characters and ‘a’ for lowercase ones.
  • The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
  • ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
  • If the character is space then print it(That is printing space character without endl which makes it to print in next line)
  • The Exit of the program.

Below is the implementation:

# Give the string as static input(which consists of only alphabets and spaces) and store it in a variable
givenstring = "Hello this is BTechGeeks"
print('The encrypted message of the given string{', givenstring, '}is :')
# Iterate through the characters of the string using For loop.
# We can calculate the ASCII value of the character using the ord() function.
for m in givenstring:
    # Now, transform each input string character to its ASCII value
    # and subtract it from the ASCII
    # value of alphabet A for uppercase characters and 'a' for lowercase ones.
    if (m >= "A" and m <= "Z"):
      # The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
        print(ord(m)-ord("A")+1, end=" ")
    elif (m >= "a" and m <= 'z'):
        # ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
        print(ord(m)-ord("a")+1, end=" ")
    # If the character is space then print it(That is printing
    # space character without endl which makes it to print in next line)
    if m == (" "):
        print(m)

Output:

The encrypted message of the given string{ Hello this is BTechGeeks }is :
8 5 12 12 15  
20 8 9 19  
9 19  
2 20 5 3 8 7 5 5 11 19

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input(which consists of only alphabets and spaces) using input() and store it in a variable.
  • Iterate through the characters of the string using For loop.
  • We can calculate the ASCII value of the character using the ord() function.
  • Now, transform each input string character to its ASCII value and subtract it from the ASCII value of alphabet A for uppercase characters and ‘a’ for lowercase ones.
  • The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
  • ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
  • If the character is space then print it(That is printing space character without endl which makes it to print in next line)
  • The Exit of the program.

Below is the implementation:

# Give the string as user input(which consists of only alphabets and spaces)
# using input() and store it in a variable.
givenstring = input('Enter some random string = ')
print('The encrypted message of the given string{', givenstring, '}is :')
# Iterate through the characters of the string using For loop.
# We can calculate the ASCII value of the character using the ord() function.
for m in givenstring:
    # Now, transform each input string character to its ASCII value
    # and subtract it from the ASCII
    # value of alphabet A for uppercase characters and 'a' for lowercase ones.
    if (m >= "A" and m <= "Z"):
      # The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
        print(ord(m)-ord("A")+1, end=" ")
    elif (m >= "a" and m <= 'z'):
        # ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
        print(ord(m)-ord("a")+1, end=" ")
    # If the character is space then print it(That is printing
    # space character without endl which makes it to print in next line)
    if m == (" "):
        print(m)

Output:

Enter some random string = btechgeeks python
The encrypted message of the given string{ btechgeeks python }is :
2 20 5 3 8 7 5 5 11 19 
16 25 20 8 15 14

Related Programs:

Python Program to Create a Class and Compute the Area and the Perimeter of the Circle

Program to Create a Class and Compute the Area and the Perimeter of the Circle

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Object-Oriented Programming(OOPS):

Object-Oriented Programming (OOP) is a programming paradigm based on the concepts of classes and objects. It is used to organize a software program into simple, reusable code blueprints (typically referred to as classes), which are then used to build individual instances of objects. Object-oriented programming languages include JavaScript, C++, Java, and Python, among others.

A class is a generic blueprint that can be used to generate more specific, concrete things. Classes are frequently used to represent broad groups, such as Cars or Dogs, that share property. These classes indicate what properties, such as color, an instance of this type will have, but not the value of those attributes for a specific object.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

Given the radius of the circle, the task is to write the python program using classes that calculate the area and perimeter of the circle.

Examples:

Example1:

Input:

given radius = 13.5

Output:

The Perimeter of circle with given radius 13.5 = 84.823
The Area of circle with given radius 13.5 = 572.5553

Example2:

Input:

given radius = 20.98

Output:

The Perimeter of circle with given radius 20.98 = 131.8212
The Area of circle with given radius 20.98 = 1382.8047

Program to Create a Class and Compute the Area and the Perimeter of the Circle

Below is the full approach for writing a Python program that creates a class with two methods that calculate the area and perimeter of the circle.

1)Using Classes(Static Input)

Approach:

  • Give the radius of the circle as static input and store it in a variable.
  • Create a class and use a parameterized constructor to initialize its value (radius of the circle).
  • Create two methods inside the class.
  • printPerimeter: which calculates the perimeter of the circle and returns it.
  • printArea: which calculates the area of the circle and returns it.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the area and perimeter of the circle are calculated and printed.
  • The Exit of the Program.

Below is the implementation:

# importing math module
import math
# creating a class


class circleClass():
  # use a parameterized constructor to initialize its value (radius of the circle).
    def __init__(self, circleradius):
        self.circleradius = circleradius
    # Create two methods inside the class.
    # printArea: which calculates the area of the circle and returns it.

    def printArea(self):
        return math.pi*(self.circleradius**2)
     # printPerimeter: which calculates the perimeter of the circle and returns it.

    def printPerimeter(self):
        return 2*math.pi*self.circleradius


# Give the radius of the circle as static input and store it in a variable.
circleradius = 13.5
# Create an object to represent the class.
circleobj = circleClass(circleradius)
# Call both methods with the object created above.
# Hence the area and perimeter of the circle are calculated and printed.
print("The Perimeter of circle with given radius",
      circleradius, '=', round(circleobj.printPerimeter(), 4))
print("The Area of circle with given radius", circleradius,
      '=', round(circleobj.printArea(), 4))

Output:

The Perimeter of circle with given radius 13.5 = 84.823
The Area of circle with given radius 13.5 = 572.5553

Explanation:

  • The radius value must be given as static input from the user.
  • A circle class is created, and the __init__() method is used to initialize the class’s values (radius of the circle.
  • The area method returns math. pi*(self. radius**2), which is the class’s area.
  • Another method, perimeter, returns 2*math. pi*self. radius, which represents the class’s perimeter.
  • The class’s object is created.
  • The methods printArea() and printPerimeter() are called using the object.
  • The area and perimeter of the circle are printed.

2)Using Classes(User Input)

Approach:

  • Give the radius of the circle as user input using float(input()) and store it in a variable.
  • Create a class and use a parameterized constructor to initialize its value (radius of the circle).
  • Create two methods inside the class.
  • printPerimeter: which calculates the perimeter of the circle and returns it.
  • printArea: which calculates the area of the circle and returns it.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the area and perimeter of the circle are calculated and printed.
  • The Exit of the Program.

Below is the implementation:

# importing math module
import math
# creating a class


class circleClass():
  # use a parameterized constructor to initialize its value (radius of the circle).
    def __init__(self, circleradius):
        self.circleradius = circleradius
    # Create two methods inside the class.
    # printArea: which calculates the area of the circle and returns it.

    def printArea(self):
        return math.pi*(self.circleradius**2)
     # printPerimeter: which calculates the perimeter of the circle and returns it.

    def printPerimeter(self):
        return 2*math.pi*self.circleradius


# Give the radius of the circle as user input using float(input()) and store it in a variable.
circleradius = float(input('Enter some random radius of the circle = '))
# Create an object to represent the class.
circleobj = circleClass(circleradius)
# Call both methods with the object created above.
# Hence the area and perimeter of the circle are calculated and printed.
print("The Perimeter of circle with given radius",
      circleradius, '=', round(circleobj.printPerimeter(), 4))
print("The Area of circle with given radius", circleradius,
      '=', round(circleobj.printArea(), 4))

Output:

Enter some random radius of the circle = 20.98
The Perimeter of circle with given radius 20.98 = 131.8212
The Area of circle with given radius 20.98 = 1382.8047

Related Programs: