CPP Programming

Program to Print Collatz Conjecture for a Given Number in C++ and Python

Program to Print Collatz Conjecture for a Given Number in C++ and Python

In the previous article, we have discussed about Program to Read a Number n and Compute n+nn+nnn in C++ and Python. Let us learn Program to Print Collatz Conjecture for a Given Number in C++ Program.

Given a number , the task is to print Collatz Conjecture of the given number in C++ and Python.

Collatz Conjecture:

  • The Collatz Conjecture states that a specific sequence will always reach the value 1.
  • It is given as follows, beginning with some integer n:
  • If n is an even number, the following number in the sequence is n/2.
  • Otherwise, the following number is 3n+1 (if n is odd).

Examples:

Example1:

Input:

given number =5425

Output:

The Collatz Conjecture of the number :
5425 16276 8138 4069 12208 6104 3052 1526 763 2290 1145 3436 1718 859 2578 1289 3868 1934 967 2902 1451 4354 2177 6532 3266 1633 4900 2450 1225 3676 1838 919 2758 1379 4138 2069 6208 3104 1552 776 388 194 97 292 146 73 220 110 55 166 83 250 125 376 188 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2  1

Example2:

Input:

given number=847

Output:

The Collatz Conjecture of the number :
847 2542 1271 3814 1907 5722 2861 8584 4292 2146 1073 3220 1610 805 2416 1208 604 302 151 454 227 682 341 1024 512 256 128 64 32 16 8 4 2  1

Program to Print Collatz Conjecture for a Given Number in C++ and Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Printing Collatz Conjecture sequence of the given number in Python

Approach:

  • Scan the given number or give number as static input.
  • Iterate till the given number is not equal to 1 using while loop.
  • Print the number numb.
  • If the number is even then set n to n/2.
  • If the number is odd then set  n to 3*n+1.
  • Print 1 after end of while loop.
  • The Exit of the Program.

Below is the implementation:

# function which prints collatz sequence of the given number
def printCollatz(numb):
  # Iterate till the given number is not equal to 1 using while loop.
    while numb > 1:
      # Print the number numb
        print(numb, end=' ')
        # If the number is even then set n to n/2.
        if (numb % 2 == 0):
            numb = numb//2
        # If the number is odd then set  n to 3*n+1.
        else:
            numb = 3*numb + 1
   # Print 1 after end of while loop.
    print(1, end='')


# given number
numb = 179
print('The Collatz Conjecture of the number :')
# passing the given numb to printCollatz function to
# print collatzConjecture sequence of the given number
printCollatz(numb)

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

2)Printing Collatz Conjecture sequence of the given number in C++

Approach:

  • Scan the given number using cin or give number as static input
  • Iterate till the given number is not equal to 1 using while loop.
  • Print the number numb.
  • If the number is even then set n to n/2.
  • If the number is odd then set  n to 3*n+1.
  • Print 1 after end of while loop.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
// function which prints collatz sequence of the given
// number
void printCollatz(int numb)
{

    // Iterate till the given number is not equal to 1 using
    // while loop.
    while (numb > 1) {
        // Print the number numb
        cout << numb << " ";
        // the number is even then set n to n / 2.
        if (numb % 2 == 0) {
            numb = numb / 2;
        }
        // the number is odd then set  n to 3 * n + 1.
        else {
            numb = 3 * numb + 1;
        }
    }
    // Print 1 after end of while loop.
    cout << " 1";
}
int main()
{

    // given number
    int numb = 179;
    cout << "The Collatz Conjecture of the number :"
         << endl;
    // passing the given numb to printCollatz function to
    // print collatzConjecture sequence of the given number
    printCollatz(numb);
    return 0;
}

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2  1

Related Programs:

Program to Reverse a String using a Stack Data Structure in C++ and Python

Program to Reverse a String using a Stack Data Structure in C++ and Python

Strings:

A string data type is used in most computer languages for data values that are made up of ordered sequences of characters, such as “hello world.” A string can include any visible or unseen series of characters, and characters can be repeated. The length of a string is the number of characters in it, and “hello world” has length 11 – made up of 10 letters and 1 space. The maximum length of a string is usually restricted. There is also the concept of an empty string, which includes no characters and has a length of zero.

A string can be both a constant and a variable. If it is a constant, it is commonly expressed as a string of characters surrounded by single or double quotes.

Stack:

Stacking objects means putting them on top of one another in the English language. This data structure allocates memory in the same manner.

Data structures are essential for organizing storage in computers so that humans can access and edit data efficiently. Stacks were among the first data structures to be defined in computer science. In layman’s terms, a stack is a linear accumulation of items. It is a collection of objects that provides fast last-in, first-out (LIFO) insertion and deletion semantics. It is a modern computer programming and CPU architecture array or list structure of function calls and parameters. Elements in a stack are added or withdrawn from the top of the stack in a “last in, first out” order, similar to a stack of dishes at a restaurant.

Unlike lists or arrays, the objects in the stack do not allow for random access.

Given a string the task is to reverse the given string using stack data structure in C++ and python.

Examples:

Example1:

Input:

given string ="hellothisisBTechGeeks"

Output:

Printing the given string before reversing : hellothisisBTechGeeks
Printing the given string after reversing : skeeGhceTBsisihtolleh

Example2:

Input:

given string ="skyisbluieIFC"

Output:

Printing the given string before reversing : skyisbluieIFC
Printing the given string after reversing : CFIeiulbsiyks

Example3:

Input:

given string="cirusfinklestein123"

Output:

Printing the given string before reversing : cirusfinklestein123
Printing the given string after reversing : 321nietselknifsuric

Program to Reverse a String using a Stack Data Structure in C++ and Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Reversing the string using stack<> function in C++

It is critical to concentrate on the algorithm in order to develop better code. This could be the initial step in selecting a problem; one must consider the optimal algorithm before moving on to the implementation and coding.

The following steps may be useful:

  • Scan the given string or given string as static input
  • The first step would be to start with an empty stack.
  • In C++, we use stack<type>, where type is the data type of the stack (like integer, character, string, etc).
  • Then, using the push function, add the characters from the string one by one to the stack, so that the last character in the string is at the top.
  • Consider a for loop that runs a certain string length number of times.
  • Using the pop() function, pop the character and replace the popped characters in the given string.
  • Print the string

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
// function which reverses the given string using stack
void revString(string& givenstr)
{
    // Taking a empty stack of character type
    stack<char> st;

    // Traversing the given string using for loop
    for (char character : givenstr) {
        // adding each element of the given string to stack
        st.push(character);
    }

    // popping all elements from the stack and
    // replacing the elements of string with the popped
    // element
    for (int i = 0; i < givenstr.length(); i++) {
        // intializing the ith character of string with the
        // top element of the stack
        givenstr[i] = st.top();
        // popping the top element from the stack using
        // pop() function
        st.pop();
    }
}

int main()
{
    // given string
    string givenstr = "hellothisisBTechGeeks";
    // printing the string before reversing elements
    cout << "Printing the given string before reversing : "
         << givenstr << endl;
    revString(givenstr);
    cout << "Printing the given string after reversing : "
         << givenstr << endl;

    return 0;
}

Output:

Printing the given string before reversing : hellothisisBTechGeeks
Printing the given string after reversing : skeeGhceTBsisihtolleh

All the characters present in the string get reversed using the above approach(including space characters).

2)Reversing the string using deque in Python

We use deque to copy all elements from the givenstring(which performs the same operation as a stack in this case)

We use the join method to join all the characters of the given string after reversing.

Below is the implementation:

from collections import deque
# given string
givenstr = "HellothisisBTechGeeks"
# Printing the given string before reversing
print("Printing the given string before reversing : ")
print(givenstr)
# creating the stack from the given string
st = deque(givenstr)

# pop all characters from the stack and join them back into a string
givenstr = ''.join(st.pop() for _ in range(len(givenstr)))

# Printing the given string after reversing
print("Printing the given string after reversing : ")
print(givenstr)

Output:

Printing the given string before reversing : 
HellothisisBTechGeeks
Printing the given string after reversing : 
skeeGhceTBsisihtolleH

Related Programs:

Program to Find Square Root of a Number in C++ and Python Programming

Python Program to Find the Square Root | Square Root in C++

Given a number ,the task is to find the square root of the given number.

Note :

Square root exists for even complex numbers too.

Examples:

Example1:

Input:

number = 16

Output:

The Square root of the given number 16 = 4.0

Example2:

Input:

number = 4 + 3 j

Output:

The Square root of the given number (4+3j) = (2.1213203435596424+0.7071067811865476j)

Example3:

Input:

number = 12

Output:

The Square root of the given number 12 = 3.4641016151377544

Program to Find Square Root of a Number

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:For Positive numbers in Python using math.sqrt function

The math module in Python’s standard library can be used to solve math problems in code. It has a lot of useful functions like remainder() and factorial() (). sqrt, the Python square root function, is also included ().

That’s what there is to it! You can now measure square roots with math.sqrt().

sqrt() has a simple user interface.

It only requires one parameter, x, which represents the square for which you are attempting to calculate the square root (as you might recall). This would be 16 in the previous case.

The square root of x as a floating point number is returned by sqrt(). This will be 4.0 in the case.

We store the number in number and use the sqrt function to find the square root in this program. This program can be used for any positive real number. However, it does not deal for negative or complex numbers.

Below is the implementation:

# importing math module
import math
# given number
number = 16
# finding square root
numberSqrt = math.sqrt(number)
# printing the square root of  given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number 16 = 4.0

Method #2:Using ** operator

We can calculate square root of a number easily by using ** operator.

Below is the implementation:

# importing math module
import math
# given number
number = 16
# finding square root
numberSqrt = number**0.5
# printing the square root of given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number 16 = 4.0

Method #3:Using sqrt function in C++

In C++, the sqrt() function returns the square root of a number.

The <cmath> header file defines this feature.
A single non-negative argument is passed to the sqrt() function.

A domain error occurs when a negative argument is passed to the sqrt() function.

Below is the implementation:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{ // given number
    float number = 16, numberSqrt;
    // calculating the square root of the given number
    numberSqrt = sqrt(number);
    // printing the square root of the given number
    cout << "The square root of the given number " << number
         << " = " << numberSqrt;

    return 0;
}

Output:

The square root of the given number 16 = 4

Method #4:Using cmath.sqrt() function in python

The sqrt() function from the cmath (complex math) module will be used in this program.

Below is the implementation:

# importing cmath module
import cmath
# given complex number
number = 4 + 3j
# finding square root of the given complex number
numberSqrt = cmath.sqrt(number)
# printing the square root of  given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number (4+3j) = (2.1213203435596424+0.7071067811865476j)

Note:

We must use the eval() function instead of float() if we want to take a complex number as input directly, such as 4+5j

In Python, the eval() method can be used to transform complex numbers into complex objects.

 
Related Programs:

What is Hashing and Hash Table

What is Hashing and Hash Table?

Hashing and Hash Table

1)Hashing

Hashing is the process of mapping object data to a representative integer value using a function or algorithm.

This hash code (or simply hash) can then be used to narrow our quest when searching for the item on the map.

These hash codes are usually used to create an index at which the value is stored.

2)Hash Table

A hash table is a data structure that stores data associatively. Data is stored in an array format in a hash table, with each data value having its own unique index value. When we know the index of the desired data, we can access it very quickly.

As a result, it becomes a data structure in which insertion and search operations are extremely quick, regardless of the size of the data. Hash Tables use an array as a storage medium and use the hash technique to produce an index from which an element is to be inserted or located.

3)Features of HashTable

  • It works in the same way as HashMap, but it is synchronised.
  • In a hash table, a key/value pair is stored.
  • In Hashtable, we define an object that will be used as a key, as well as the value that will be associated with that key. The key is then hashed, and the resulting hash code serves as the index for storing the value in the table.
  • The default capacity of the Hashtable class is 11, and the loadFactor is 0.75.
  • HashMap does not support Enumeration, while Hashtable does not support fail-fast Enumeration.

4)Adding element in HashTable

When an entity is inserted into a Hash Table, its hash code is measured first, and the bucket in which it will be stored is determined based on that hash code.

Let us illustrate this with an example.

For instance, suppose we want to store some numbers in a Hash Table, i.e.

32 , 45 , 64 , 92 , 57 , 88 , 73

Internally, this Hash Table can use 10 buckets, i.e.

The Hash Code will be returned by our Hash Function.

HashCode=Element_value%10

This Hash code for,

32 will be 2

45 will be 5

64 will be 4

92 will be 2

57 will be 7

88 will be 8

73 will be 3

Now, each element’s hash code will be used to determine where that element will be stored, for example, 45 will be stored in bucket 5 since its hash code is 5. In the same way, all elements will be stored in the bucket that corresponds to their hash code.

5)Hashing Collisions

As we can see, the hash code for both 32 and 92 is the same, which is 2. In Hashing, this is referred to as Collision. Both components would be deposited in the same bucket if they collide.

6)Searching element in Hash Table

If we want to check for an element in a hash table, we must first calculate the hash code for that element. Then, using the hash code, we’ll go straight to the bucket where this element will be saved. Now, there may be several elements in that bucket; in that case, we’ll look for our element only in those elements.

Assume we want to find 45 in the hash table in the previous case.

Then we’ll measure the hash code, which will be 45 %10 = 5.

Then we’ll go straight to bucket no. 5 and search for the factor there.

7)Best Case Time Complexity in Hashing

From the viewpoint of searching, each bucket containing only one element in the Hash table is the best case scenario. In such a case, searching time would require the following effort:

The complexity of calculating hash codes is O(1)

If the bucket only contains one element, choosing that element from the bucket is a complex task O(1)

Consequently In the best case scenario, finding an element would be difficult O(1)

While the complexity of a collision, i.e. several elements in a bucket, will be O(no. of elements in bucket), it will be much less than the complexity of searching an element from a List, which will be O(n).

8)Worst Case Time Complexity in Hashing

The worst case scenario in hashing is when the Hash Function is not correctly implemented, resulting in the same hash code for several elements.

Assume the following is our hash function:

Hash code = given_element / 100

Then, in the preceding case, the hash code for all elements ( 32 , 45 , 64 , 92 , 57 , 88 , 73 ) will be 0. As a result, all elements will be saved in bucket 0.

Since all components are in the same bucket, complexity is at its highest in this case. As a result, the complexity will be O(n) since it must check for the appropriate element among all elements.

Related Programs:

Linked List Data Structure

Linked List Data Structure:

A linked list is a type of data structure that consists of a chain of nodes, each of which contains a value and a pointer to the next node in the chain.

The list’s head pointer points to the first node, and the list’s last element points to null. The head pointer points to null when the list is empty.

Linked lists can grow in size dynamically, and inserting and deleting elements from them is simple because, unlike arrays, we only need to change the pointers to the previous and next elements to insert or delete an element.

Linked lists are commonly used in the construction of file systems, adjacency lists, and hash tables.

Why Linked List?

Arrays can be used to store similar types of linear data, but they have the following limitations.
1) Because the array size is fixed, we must know the maximum number of elements in advance. Furthermore, regardless of usage, the allocated memory is always equal to the upper limit.
2) Inserting a new element in an array of elements is expensive because room must be made for the new elements, and existing elements must be shifted to make room, whereas in a linked list if we have the head node, we can traverse to any node through it and insert a new node at the required position.

Advantages of Linked Lists over arrays

1)Dynamic Data Structure:

  • Because the linked list is a dynamic data structure that can shrink and grow at runtime by deallocating or allocating memory, there is no need for initial size.
  • In contrast, in an array, an initial size must be declared, and the number of elements cannot exceed that size.

2) No Memory Wastage:

  • There is no memory waste because the size of a linked list can grow or shrink at runtime. Only the necessary memory is allocated.
  • In arrays, we must first initialize it with a size that we may or may not fully utilize. Thus, memory waste may occur.

3)Implementation:

A Linked List can be used to easily implement some very useful data structures such as queues and stacks.

4)Insertion and Deletion Operation:

Insertion and deletion operations in a Linked List are simple because there is no need to shift every element after insertion or deletion. Only the address in the pointers needs to be changed.

Disadvantages of Linked Lists over arrays

1)Memory Usage:

A linked list requires more memory than an array because it includes a pointer field in addition to the data field. The pointer field, like all other fields, requires memory to store the address of the next node.

2)Random Access:

To get to node an at index x in a linked list, we must first go through all the nodes before it. In the case of an array, however, we can use arr[x] to directly access an element at index x.

3)Reverse Traversal:

  • Reverse traversal is not possible in a singly linked list because each node stores only the address of the next node. Reverse traversal is possible in the case of a doubly-linked list, but it consumes more memory because we must allocate extra memory to store the previous pointer.
  • With the help of a for loop, we can perform a simple reverse traversal in arrays.

Representation:

A pointer to the first node of a linked list is used to represent it. The first node is referred to as the head. When the linked list is empty, the value of the head is NULL.
A list node is made up of at least two parts:
1) data (we can store integers, strings, or any type of data).
2) A pointer to the next node (or a reference to it) (connects one node to another)

Example Node of a Linked List

Program for Multiplication of Two Matrices in Python and C++ Programming

Python Program for Multiplication of Two Matrices | How do you do Matrix Multiplication in Python?

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Looking across the web for guidance on Multiplication of Two Matrices in Python? Before you begin your learning on Matrix Multiplication of Two Matrices know what is meant by a Matrix and what does Matrix Multiplication in actual means. This tutorial is going to be extremely helpful for you as it assists you completely on How to Multiply Two Matrices in Python using different methods like nested loops, nested list comprehension, etc. Furthermore, we have written simple python programs for multiplying two matrices clearly.

What is a Matrix?

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

What is Matrix Multiplication?

Matrix multiplication is only possible if the second matrix’s column equals the first matrix’s rows. A matrix can be represented in Python as a nested list ( a list inside a list ).

Examples for Matrix Multiplication:

Example 1:

Input:

Matrix 1  =  [  1  -8    7  ]
                    [  0   2    5  ]
                    [  1   6    2 ]
                      
Matrix 2 =   [   5    2   -6  ]
                    [   1    8    9 ]
                    [   3    5    7 ]

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Example 2:

Input:

Matrix 1  =  1 2 3 
                  -5 8 7 
                   6 4 5 
                      
Matrix 2 =  2 7 9 
                  0 -8 5 
                  6 -5 2

Output:

Enter the number of rows and columns of the first matrix3
3
Enter the number of rows and columns of the second matrix3
3
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = -5
Enter element A22 = 8
Enter element A23 = 7
Enter element A31 = 6
Enter element A32 = 4
Enter element A33 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 2
Enter element B12 = 7
Enter element B13 = 9
Enter element B21 = 0
Enter element B22 = -8
Enter element B23 = 5
Enter element B31 = 6
Enter element B32 = -5
Enter element B33 = 2

printing the matrix A
1 2 3 
-5 8 7 
6 4 5

printing the matrix B
2 7 9 
0 -8 5 
6 -5 2 
Print the product of two matrices A and B
20 -24 25 
32 -134 9 
42 -15 84

Given two matrices, the task is to write a program in Python and C++ to multiply the two matrices.

Simple Python Program for Matrix Multiplication

Method #1: Using Nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list).

Each element can be thought of as a row in the matrix.

X[0] can be used to choose the first row. Furthermore, the element in the first row, the first column can be chosen as X[0][0].

The multiplication of two matrices X and Y is defined if the number of columns in X equals the number of rows in Y.

Here we give the matrix input as static.

XY is defined and has the dimension n x l if X is a n x m matrix and Y is a m x l matrix (but YX is not defined). In Python, there are a few different approaches to implement matrix multiplication.

Below is the  implementation:

# given matrix A
A = [[1, - 8, 7],
     [0, 2, 5],
     [1, 6, 2]]
# given matrix B
B = [[5, 2, - 6],
     [1, 8, 9],
     [3, 5, 7]]
# Initialize the product of matrices elements to 0
matrixProduct = [[0, 0, 0],
                 [0, 0, 0],
                 [0, 0, 0]]
# Traverse the rows of A
for i in range(len(A)):
    #  Traverse the  columns of B
    for j in range(len(B[0])):
        # Traverse the  rows of B
        for k in range(len(B)):
            matrixProduct[i][j] += A[i][k] * B[k][j]
# printing the matrix A
print("printing the matrix A :")
for rows in A:
    print(*rows)
# printing the matrix B
print("printing the matrix B :")
for rows in B:
    print(*rows)
# printing the product of matrices
print("Printing the product of matrices : ")
for rows in matrixProduct:
    print(*rows)

Python Program for Matrix Multiplication using Nested Loops

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Explanation:

To go through each row and column in our program, we used nested for loops. In the end, we add up the sum of the items.

This technique is simple, but it becomes computationally expensive as the order of the matrix increases.

We recommend NumPy for larger matrix operations because it is several (in the order of 1000) times faster than the above code.

Method #2: Matrix Multiplication List Comprehension Python

This program produces the same results as the previous one. To understand the preceding code, we must first know the built-in method zip() and how to unpack an argument list with the * operator.

To loop through each element in the matrix, we utilized nested list comprehension. At first glance, the code appears to be complicated and difficult to understand. However, once you’ve learned list comprehensions, you won’t want to go back to nested loops.

Below is the implementation:

# given matrix A
A = [[1, - 8, 7],
     [0, 2, 5],
     [1, 6, 2]]
# given matrix B
B = [[5, 2, - 6],
     [1, 8, 9],
     [3, 5, 7]]
# using list comprehension to do product of matrices
matrixProduct = [[sum(a*b for a, b in zip(row, col))
                  for col in zip(*B)] for row in A]

# printing the matrix A
print("printing the matrix A :")
for rows in A:
    print(*rows)
# printing the matrix B
print("printing the matrix B :")
for rows in B:
    print(*rows)
# printing the product of matrices
print("Printing the product of matrices : ")
for rows in matrixProduct:
    print(*rows)

Python Program for Matrix Multiplication using List Comprehension

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Method #3: Using Nested Loops in C++

We used nesting loops in this program to iterate through and row and column. In order to multiply two matrices, we will do the multiplication of matrices as below

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    int A[100][100], B[100][100], product[100][100], row1,
        col1, row2, col2, i, j, k;

    cout << "Enter the number of rows and columns of the "
            "first matrix";
    cin >> row1 >> col1;
    cout << "Enter the number of rows and columns of the "
            "second matrix";
    cin >> row2 >> col2;

    // Initializing matrix A with the user defined values
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col1; ++j) {
            cout << "Enter element A" << i + 1 << j + 1
                 << " = ";
            cin >> A[i][j];
        }
    // Initializing matrix B with the user defined values
    cout << endl
         << "Enter elements of 2nd matrix: " << endl;
    for (i = 0; i < row2; ++i)
        for (j = 0; j < col2; ++j) {
            cout << "Enter element B" << i + 1 << j + 1
                 << " = ";
            cin >> B[i][j];
        }

    // Initializing the resultant product matrix with 0 to
    // all elements
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col2; ++j) {
            product[i][j] = 0;
        }

    // Calculating the product of two matrices A and B
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col2; ++j)
            for (k = 0; k < col1; ++k) {
                product[i][j] += A[i][k] * B[k][j];
            }
    // printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < row1; ++i) {
        for (j = 0; j < col1; ++j) {
            cout << A[i][j] << "  ";
        }
        cout << endl;
    }
    // printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < row2; ++i) {
        for (j = 0; j < col2; ++j) {
            cout << B[i][j] << "  ";
        }
        cout << endl;
    }

    // Print the product of two matrices A and B
    cout << "Print the product of two matrices A and B"
         << endl;
    for (i = 0; i < row1; ++i) {
        for (j = 0; j < col2; ++j) {
            cout << product[i][j] << "  ";
        }
        cout << endl;
    }

    return 0;
}

Output:

Enter the number of rows and columns of the first matrix3
3
Enter the number of rows and columns of the second matrix3
3
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = -5
Enter element A22 = 8
Enter element A23 = 7
Enter element A31 = 6
Enter element A32 = 4
Enter element A33 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 2
Enter element B12 = 7
Enter element B13 = 9
Enter element B21 = 0
Enter element B22 = -8
Enter element B23 = 5
Enter element B31 = 6
Enter element B32 = -5
Enter element B33 = 2

printing the matrix A
1 2 3 
-5 8 7 
6 4 5

printing the matrix B
2 7 9 
0 -8 5 
6 -5 2 
Print the product of two matrices A and B
20 -24 25 
32 -134 9 
42 -15 84

How to Multiply Two Matrices in Python using Numpy?

import numpy as np

C = np.array([[3, 6, 7], [5, -3, 0]])
D = np.array([[1, 1], [2, 1], [3, -3]])
E = C.dot(D)
print(E)

''' 

Output:

[[ 36 -12]
[ -1 2]]

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Related Programs:

Write a Program for Matrix Subtraction

Program to Subtract two Matrices in Python & C++ Programming

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called as 5*4 matrix.

What is matrix subtraction:

Given two matrices of same order(dimensions) then we can easily add the two matrices by doing the difference of corresponding elements in both the matrices.

Example:

 

Here Matrix C is matrix subtraction  of the matrices A and B.

Examples for matrix addition:

Input:

Matrix 1  =    2    3   1
                      1    2   3
                     -3   0   2    
Matrix 2 =      1    4    2
                     -4    5   -1
                      2    1     4

Output:

Printing the difference of matrices : 
1 -1 -1
5 -3 4
-5 -1 -2

Explanation:

 Here we subtracted the corresponding elements in both matrices

Program for Matrix Subtraction

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list). Each variable can be thought of as a row in the matrix.

Approach:

  • Create two two-dimensional arrays, a and b, and set their values. (In this case, we used a  initialised statically)
  • Calculate the number of rows and columns in the array a (since the dimensions of both arrays are the same) and store it in the variables rows and columns.
    Declare a new array diff, this time with dimensions in rows and columns.
  • Calculate the difference between the respective elements by looping around the arrays a and b.
  • Print the difference of two matrices.

Below is the  implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3],
     [-3, 0, 2]]
# given matrix B
B = [[1, 4, 2],
     [-4, 5, -1],
     [2, 1, 4]]
# Initialize the difference of matrices elements to 0
matrixDiff = [[0, 0, 0],
              [0, 0, 0],
              [0, 0, 0]]
# Traverse the rows
for rows in range(len(A)):
    # Traverse the  columns
    for columns in range(len(A[0])):
        matrixDiff[rows][columns] = A[rows][columns] - B[rows][columns]
# printing the difference of matrices
print("Printing the difference of matrices : ")
for rows in matrixDiff:
    print(*rows)

Output:

Printing the difference of matrices : 
1 -1 -1
5 -3 4
-5 -1 -2

Method #2:Using List Comprehension in Python

The program’s output is the same as previously. For iterating through each element in the array, we used the nested list comprehension.

Understanding the list helps us to write concise codes and we need to always try to use them in Python. They’re really beneficial.

Below is the implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3],
     [-3, 0, 2]]
# given matrix B
B = [[1, 4, 2],
     [-4, 5, -1],
     [2, 1, 4]]
# Initialize the difference of matrices elements to 0
matrixDiff = [[0, 0, 0],
              [0, 0, 0],
              [0, 0, 0]]

# using list comprehension
matrixDiff = [[A[i][j] - B[i][j]
               for j in range(len(A[0]))] for i in range(len(A))]

# printing the difference of matrices
print("Printing the difference of matrices : ")
for rows in matrixDiff:
    print(*rows)

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Method #3:Using nested loops in C++

We used nesting loops in this program to iterate through and row and column. In the two matrices we will subract the appropriate elements and store them in the result at each level.

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{
    int rows, columns, A[100][100], B[100][100], DiffMatrix[100][100], i, j;
    cout << "Enter the number of rows of the matrix "<<endl;
    cin >> rows;
    cout << "Enter the number of columns of the matrix"<<endl;
    cin >> columns;
    cout << "Enter the elements of first matrix " << endl;
    // Initializing matrix A with the user defined values
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element A" << i + 1 << j + 1 << " = ";
           cin >> A[i][j];
       }
   // Initializing matrix B with the user defined values
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element B" << i + 1 << j + 1 << " = ";
           cin >> B[i][j];
       }
    // Performing matrix addition by doing diffeerence of given two matrices A and B
    for(i = 0; i < rows; ++i)
        for(j = 0; j < columns; ++j)
            DiffMatrix[i][j] = A[i][j] - B[i][j];
    //printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << A[i][j] << "  ";
    }
    cout << endl;
}
    //printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << B[i][j] << "  ";
    }
    cout << endl;
}
    //printing the difference of matrices
    cout << endl << " printing the difference of matrices A and B" << endl;
    
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << DiffMatrix[i][j] << "  ";
    }
    cout << endl;
}
    return 0;
}

Output:

Enter the number of rows of the matrix 
4
Enter the number of columns of the matrix
4
Enter the elements of first matrix 
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A14 = 4
Enter element A21 = 5
Enter element A22 = 6
Enter element A23 = 5
Enter element A24 = 2
Enter element A31 = -5
Enter element A32 = 9
Enter element A33 = 1
Enter element A34 = 5
Enter element A41 = 0
Enter element A42 = 5
Enter element A43 = 2
Enter element A44 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 1
Enter element B12 = 9
Enter element B13 = 5
Enter element B14 = 3
Enter element B21 = 8
Enter element B22 = -4
Enter element B23 = -8
Enter element B24 = 0
Enter element B31 = 5
Enter element B32 = 1
Enter element B33 = 7
Enter element B34 = -3
Enter element B41 = -8
Enter element B42 = 1
Enter element B43 = 2
Enter element B44 = 0

printing the matrix A
1 2 3 4 
5 6 5 2 
-5 9 1 54 
0 5 2 5

printing the matrix B
1 9 5 3 
8 -4 -38 0 
5 1 7 -3 
-8 1 2 0

printing the difference of matrices A and B
0 -7 -2 1 
-3 10 43 2 
-10 8 -6 57 
8 4 0 5

Related Programs:

Python Program to Print Square Pattern with Numbers

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Given the number of rows, the task is to print Square Pattern with Numbers in C, C++, and Python

Examples:

Example1:

Input:

Given number of rows = 9

Output:

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

Example2:

Input:

Given number of rows = 6

Output:

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

Program to Print Square Pattern with Numbers in C, C++, and Python

Below are the ways to print Square Pattern with 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 1 to the number of rows using another for loop(Nested For loop).
  • Check if the iterator value of the inner For loop is less than or equal to the parent loop iterator value of theFor Loop using the If conditional Statement.
  • If it is true then print the iterator value of the parent For loop.
  • Else 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 = 9
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows+1):
    # Loop from 1 to the number of rows using another for loop(Nested For loop).
    for n in range(1, numbrrows+1):
        ''' Check if the iterator value of the inner For loop is less than or equal 
            to the parent loop iterator value of the
            For Loop using the If conditional Statement.'''
        if(n <= m):
            # If it is true then print the iterator value of the parent For loop.
            print(m, end=' ')
        else:
            print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

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

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 = 5;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numbrrows; m++) {
        // Loop from 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                cout << m << " ";
            else
                cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }
    return 0;
}

Output:

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

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 = 3;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numbrrows; m++) {
        // Loop from 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                printf("%d ", m);
            else
                printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

1 2 3 
2 2 3 
3 3 3

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 1 to the number of rows using another for loop(Nested For loop).
  • Check if the iterator value of the inner For loop is less than or equal to the parent loop iterator value of theFor Loop using the If conditional Statement.
  • If it is true then print the iterator value of the parent For loop.
  • Else 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+1):
    # Loop from 1 to the number of rows using another for loop(Nested For loop).
    for n in range(1, numbrrows+1):
        ''' Check if the iterator value of the inner For loop is less than or equal 
            to the parent loop iterator value of the
            For Loop using the If conditional Statement.'''
        if(n <= m):
            # If it is true then print the iterator value of the parent For loop.
            print(m, end=' ')
        else:
            print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

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

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
    // int(input()) 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 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                cout << m << " ";
            else
                cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }
    return 0;
}

Output:

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

3) C Implementation

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

Below is the implementation:

#include <math.h>
#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 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                printf("%d ", m);
            else
                printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

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

Related Programs:

Python Program to Print Inverted Pyramid Pattern with the Same Digit

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Given the number of rows, the task is to print Inverted Pyramid Pattern with the same digit in C,C++, and Python

Examples:

Example1:

Input:

Given number of rows = 10

Output:

10 10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 
10 10 10 10 10 10 
10 10 10 10 10 
10 10 10 10 
10 10 10 
10 10 
10

Example2:

Input:

Given number of rows = 9

Output:

9 9 9 9 9 9 9 9 9 
9 9 9 9 9 9 9 9 
9 9 9 9 9 9 9 
9 9 9 9 9 9 
9 9 9 9 9 
9 9 9 9 
9 9 9 
9 9 
9

Program to Print Inverted Pyramid Pattern with the Same Digit in C, C++, and Python

Below are the ways to Program to Print Inverted Pyramid patterns with the Same Digit 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.
  • Take a variable and store the given number of rows in it say givennumbrows.
  • Loop from the number of rows to 0 in decreasing order using For loop.
  • Loop from 0 to the parent loop iterator using another For loop(Nested For Loop).
  • Print the givennumbrows.
  • 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 = 7
# Take a variable and store the given number of rows in it say givennumbrows.
givennumbrows = numbrrows
# Loop from the number of rows to 0 in decreasing order using For loop.
for m in range(numbrrows, 0, -1):
    # Loop from 0 to the parent loop iterator using another For loop(Nested For Loop).
    for n in range(0, m):
        # Print the givennumbrows.
        print(givennumbrows, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

7 7 7 7 7 7 7 
7 7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 
7 7 7 
7 7 
7

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;
    // Take a variable and store the given number of rows in
    // it say givennumbrows.
    int givennumbrows = numbrrows;
    // Loop from the number of rows to 0 in decreasing
    // order using For loop.
    for (int m = numbrrows; m > 0; m--) {
        // Loop from 0 to the parent loop iterator using
        // another For loop(Nested For Loop).
        for (int n = 0; n < m; n++) {
            // Print the givennumbrows.
            cout << givennumbrows << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }
    return 0;
}

Output:

10 10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 
10 10 10 10 10 10 
10 10 10 10 10 
10 10 10 10 
10 10 10 
10 10 
10

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 = 4;
    // Take a variable and store the given number of rows in
    // it say givennumbrows.
    int givennumbrows = numbrrows;
    // Loop from the number of rows to 0 in decreasing
    // order using For loop.
    for (int m = numbrrows; m > 0; m--) {
        // Loop from 0 to the parent loop iterator using
        // another For loop(Nested For Loop).
        for (int n = 0; n < m; n++) {
            // Print the givennumbrows.
            printf("%d ", givennumbrows);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

4 4 4 4 
4 4 4 
4 4 
4

Method #2: Using For Loop (User Input)

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 = '))
# Take a variable and store the given number of rows in it say givennumbrows.
givennumbrows = numbrrows
# Loop from the number of rows to 0 in decreasing order using For loop.
for m in range(numbrrows, 0, -1):
    # Loop from 0 to the parent loop iterator using another For loop(Nested For Loop).
    for n in range(0, m):
        # Print the givennumbrows.
        print(givennumbrows, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 10
10 10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 
10 10 10 10 10 10 
10 10 10 10 10 
10 10 10 10 
10 10 10 
10 10 
10

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
    // int(input()) and store it in a variable.
    int numbrrows;
    cin >> numbrrows;
    // Take a variable and store the given number of rows in
    // it say givennumbrows.
    int givennumbrows = numbrrows;
    // Loop from the number of rows to 0 in decreasing
    // order using For loop.
    for (int m = numbrrows; m > 0; m--) {
        // Loop from 0 to the parent loop iterator using
        // another For loop(Nested For Loop).
        for (int n = 0; n < m; n++) {
            // Print the givennumbrows.
            cout << givennumbrows << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

10
10 10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 
10 10 10 10 10 10 
10 10 10 10 10 
10 10 10 10 
10 10 10 
10 10 
10

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);
    // Take a variable and store the given number of rows in
    // it say givennumbrows.
    int givennumbrows = numbrrows;
    // Loop from the number of rows to 0 in decreasing
    // order using For loop.
    for (int m = numbrrows; m > 0; m--) {
        // Loop from 0 to the parent loop iterator using
        // another For loop(Nested For Loop).
        for (int n = 0; n < m; n++) {
            // Print the givennumbrows.
            printf("%d ", givennumbrows);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

9
9 9 9 9 9 9 9 9 9 
9 9 9 9 9 9 9 9 
9 9 9 9 9 9 9 
9 9 9 9 9 9 
9 9 9 9 9 
9 9 9 9 
9 9 9 
9 9 
9

Related Programs:

Python Program to Print Pattern with a Combination of Numbers and Stars

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Given the number of rows, the task is to Print pattern with a combination of Numbers and Stars in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 8

Output:

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

Example2:

Input:

Given number of rows = 13

Output:

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

Program to Print Pattern with a Combination of Numbers and Stars in C, C++, and Python

Below are the ways to print Print Pattern with a Combination of Numbers and Stars 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 0 to the number of rows using For loop.
  • Inside the For, loop Take a variable(say Tempo) and initialize its value with 1.
  • Print the value of the Tempo variable with space.
  • Loop from the number of rows -m-1 to 0 in decreasing order using another for loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the Star Character with space.
  • Increment the value of Tempo by 1.
  • Print the value of the Tempo variable with space.
  • 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.
numberOfRows = 8
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Inside the For, loop Take a variable(say Tempo) and initialize its value with 1.
    Tempo = 1
    # Print the value of the Tempo variable with space.
    print(Tempo, end=' ')
    # Loop from the number of rows -m-1 to 0 in decreasing order using another for loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(numberOfRows-m-1, 0, -1):
      # Print the Star Character with space.
        print('*', end=' ')
        # Increment the value of Tempo by 1.
        Tempo = Tempo + 1
        # Print the value of the Tempo variable with space.
        print(Tempo, end=' ')

    # Print the Newline character after the end of the inner loop.
    print()

Output:

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

2) C++ Implementation

Below is the implementation:

#include <iostream>
#include <math.h>
using namespace std;
int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;
    // Loop from 0 to the number of rows using For loop.

    for (int m = 0; m < numberOfRows; m++) {
        // Inside the For, loop Take a variable(say Tempo)
        // and initialize its value with 1.
        int Tempo = 1;
        // Print the value of the Tempo variable with space.
        cout << Tempo << " ";
        // Loop from the number of rows -m-1 to 0 in
        // decreasing order using another
        // for loop(Nested For loop)
        // where m is the iterator value of the parent For
        // loop.
        for (int n = numberOfRows - m - 1; n > 0; n--) {
            // Print the Star Character with space.
            cout << "* ";
            // Increment the value of Tempo by 1.
            Tempo = Tempo + 1;
            // Print the value of the Tempo variable with
            ///space.
            cout << Tempo << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 
1 * 2 * 3 * 4 * 5 * 6 * 7 
1 * 2 * 3 * 4 * 5 * 6 
1 * 2 * 3 * 4 * 5 
1 * 2 * 3 * 4 
1 * 2 * 3 
1 * 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 numberOfRows = 13;
    // Loop from 0 to the number of rows using For loop.

    for (int m = 0; m < numberOfRows; m++) {
        // Inside the For, loop Take a variable(say Tempo)
        // and initialize its value with 1.
        int Tempo = 1;
        // Print the value of the Tempo variable with space.
        printf("%d ", Tempo);
        // Loop from the number of rows -m-1 to 0 in
        // decreasing order using another
        // for loop(Nested For loop)
        // where m is the iterator value of the parent For
        // loop.
        for (int n = numberOfRows - m - 1; n > 0; n--) {
            // Print the Star Character with space.
            printf("* ");
            // Increment the value of Tempo by 1.
            Tempo = Tempo + 1;
            // Print the value of the Tempo variable with
            /// space.
            printf("%d ", Tempo);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 
1 * 2 * 3 * 4 * 5 * 6 * 7 
1 * 2 * 3 * 4 * 5 * 6 
1 * 2 * 3 * 4 * 5 
1 * 2 * 3 * 4 
1 * 2 * 3 
1 * 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 0 to the number of rows using For loop.
  • Inside the For, loop Take a variable(say Tempo) and initialize its value with 1.
  • Print the value of the Tempo variable with space.
  • Loop from the number of rows -m-1 to 0 in decreasing order using another for loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the Star Character with space.
  • Increment the value of Tempo by 1.
  • Print the value of the Tempo variable with space.
  • 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.
numberOfRows = int(input('Enter some random number of rows = '))
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Inside the For, loop Take a variable(say Tempo) and initialize its value with 1.
    Tempo = 1
    # Print the value of the Tempo variable with space.
    print(Tempo, end=' ')
    # Loop from the number of rows -m-1 to 0 in decreasing order using another for loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(numberOfRows-m-1, 0, -1):
      # Print the Star Character with space.
        print('*', end=' ')
        # Increment the value of Tempo by 1.
        Tempo = Tempo + 1
        # Print the value of the Tempo variable with space.
        print(Tempo, end=' ')

    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 11
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 
1 * 2 * 3 * 4 * 5 * 6 * 7 
1 * 2 * 3 * 4 * 5 * 6 
1 * 2 * 3 * 4 * 5 
1 * 2 * 3 * 4 
1 * 2 * 3 
1 * 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
    // int(input()) and store it in a variable.
    int numberOfRows;
    cin >> numberOfRows;
    // Loop from 0 to the number of rows using For loop.

    for (int m = 0; m < numberOfRows; m++) {
        // Inside the For, loop Take a variable(say Tempo)
        // and initialize its value with 1.
        int Tempo = 1;
        // Print the value of the Tempo variable with space.
        cout << Tempo << " ";
        // Loop from the number of rows -m-1 to 0 in
        // decreasing order using another
        // for loop(Nested For loop)
        // where m is the iterator value of the parent For
        // loop.
        for (int n = numberOfRows - m - 1; n > 0; n--) {
            // Print the Star Character with space.
            cout << "* ";
            // Increment the value of Tempo by 1.
            Tempo = Tempo + 1;
            // Print the value of the Tempo variable with
            /// space.
            cout << Tempo << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

5
1 * 2 * 3 * 4 * 5 
1 * 2 * 3 * 4 
1 * 2 * 3 
1 * 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 numberOfRows;
    scanf("%d", &numberOfRows);
   // Loop from 0 to the number of rows using For loop.

    for (int m = 0; m < numberOfRows; m++) {
        // Inside the For, loop Take a variable(say Tempo)
        // and initialize its value with 1.
        int Tempo = 1;
        // Print the value of the Tempo variable with space.
        printf("%d ", Tempo);
        // Loop from the number of rows -m-1 to 0 in
        // decreasing order using another
        // for loop(Nested For loop)
        // where m is the iterator value of the parent For
        // loop.
        for (int n = numberOfRows - m - 1; n > 0; n--) {
            // Print the Star Character with space.
            printf("* ");
            // Increment the value of Tempo by 1.
            Tempo = Tempo + 1;
            // Print the value of the Tempo variable with
            /// space.
            printf("%d ", Tempo);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

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

Related Programs: