Write a program to Replace Array Elements by Given Value in C
Write a program to Replace Array Elements by Given Value in C++
Write a program to Replace Array Elements by Given Value in Python
Write a program to Replace Array Elements by Given Value in PHP
Write a program to Replace Array Elements by Given Value in Java
Write a program to Replace Array Elements by Given Value in Java Script
Write a program to Replace Array Elements by Given Value in C#
Explanation:
Logic:
Iterate Through the Array:
For each element in the array:
If the element matches the target value, replace it with the new value.
Modify the Array In-Place:
Update the elements directly if in-place modification is required.
Alternatively, create a new array with the replaced elements if immutability is desired.
Program to Replace Array Elements by Given Value
C
C++
Python
PHP
JAVA
Java Script
C#
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // Example array
int size = sizeof(arr) / sizeof(arr[0]);
int value = 10; // Value to replace array elements with
for (int i = 0; i < size; i++) {
arr[i] = value;
}
printf("Array after replacement: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5}; // Example array
int size = sizeof(arr) / sizeof(arr[0]);
int value = 10; // Value to replace array elements with
for (int i = 0; i < size; i++) {
arr[i] = value;
}
cout << "Array after replacement: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
arr = [1, 2, 3, 4, 5] # Example array
value = 10 # Value to replace array elements with
arr = [value] * len(arr) # Replace all elements with the given value
print("Array after replacement:", arr)
<?php
$arr = array(1, 2, 3, 4, 5); // Example array
$value = 10; // Value to replace array elements with
$arr = array_fill(0, count($arr), $value); // Replace all elements with the given value
echo "Array after replacement: ";
print_r($arr);
?>
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Example array
int value = 10; // Value to replace array elements with
for (int i = 0; i < arr.length; i++) {
arr[i] = value;
}
System.out.print("Array after replacement: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
const arr = [1, 2, 3, 4, 5]; // Example array
const value = 10; // Value to replace array elements with
arr.fill(value); // Replace all elements with the given value
console.log("Array after replacement:", arr);
using System;
class Program {
static void Main() {
int[] arr = {1, 2, 3, 4, 5}; // Example array
int value = 10; // Value to replace array elements with
for (int i = 0; i < arr.Length; i++) {
arr[i] = value;
}
Console.Write("Array after replacement: ");
foreach (int num in arr) {
Console.Write(num + " ");
}
Console.WriteLine();
}
}