Given two integers X and N, print the value X on the screen N times. Move to the next line after printing, even if N = 0.
Input: X = 7, N = 5
Output: 7 7 7 7 7
Input: X = 15, N = 1
Output: 15
Input: X = -5, N = 4
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to print the value X on the screen N times
void printX(int X, int N) {
// Check if N is non-negative
if (N < 0) {
cout << "Invalid number of times" << endl;
return;
}
// Loop to print the value X, N times
for (int i = 0; i < N; ++i) {
// Print the value X
cout << X;
/* Print a space between numbers,
but not after the last one */
if (i < N - 1) {
cout << " ";
}
}
// Move to the next line after printing
cout << endl;
}
};
int main() {
// Creating an instance of Solution class
Solution sol;
int X = 7, N = 5;
// Function call to print the value X, N times
sol.printX(X, N);
return 0;
}
class Solution {
// Function to print the value X on the screen N times
public void printX(int X, int N) {
// Check if N is non-negative
if (N < 0) {
System.out.println("Invalid number of times");
return;
}
// Loop to print the value X, N times
for (int i = 0; i < N; ++i) {
// Print the value X
System.out.print(X);
/* Print a space between numbers,
but not after the last one */
if (i < N - 1) {
System.out.print(" ");
}
}
// Move to the next line after printing
System.out.println();
}
public static void main(String[] args) {
// Creating an instance of Solution class
Solution sol = new Solution();
int X = 7, N = 5;
// Function call to print the value X, N times
sol.printX(X, N);
}
}
class Solution:
# Function to print the value X on the screen N times
def printX(self, X, N):
# Check if N is non-negative
if N < 0:
print("Invalid number of times")
return
# Loop to print the value X, N times
for i in range(N):
# Print the value X
print(X, end='')
# Print a space between numbers,
# but not after the last one
if i < N - 1:
print(" ", end='')
# Move to the next line after printing
print()
# Creating an instance of Solution class
sol = Solution()
X = 7
N = 5
# Function call to print the value X, N times
sol.printX(X, N)
class Solution {
// Function to print the value X on the screen N times
printX(X, N) {
// Check if N is non-negative
if (N < 0) {
console.log("Invalid number of times");
return;
}
// Loop to print the value X, N times
for (let i = 0; i < N; ++i) {
// Print the value X
process.stdout.write(X.toString());
/* Print a space between numbers,
but not after the last one */
if (i < N - 1) {
process.stdout.write(" ");
}
}
// Move to the next line after printing
console.log();
}
}
// Creating an instance of Solution class
const sol = new Solution();
const X = 7, N = 5;
// Function call to print the value X, N times
sol.printX(X, N);