打印Java中奇数位置存在的数组元素
在Java中,数组是一个对象。它是一种非基本数据类型,用于存储相同数据类型的多个值。
根据题意,我们需要找到数组中位于奇数位置的元素并打印它们。
如果一个数字能被2整除,则称其为偶数;否则,称其为奇数。
注意 − 数组必须是整数数组。
让我们一起学习如何使用Java编程语言来实现这一点。
一些示例
示例1
Suppose the original array is {12, 5, 77, 14, 91, 21, 1, 50}
找到数组中奇数位置的元素后,结果将是:
Odd position of elements present in an array are: [5, 14, 21, 50]
示例2
Suppose the original array is {12, 23, 11, 64, 5, 87, 22, 67, 100};
找到数组中奇数位置的元素后,结果将是:
Odd position of elements present in an array are: [23, 64, 87, 67]
示例3
Suppose the original array is {11, 22, 33, 44, 55}
找到数组中奇数位置的元素后,结果将是:
Odd position of elements present in an array are: [22, 44]
算法
步骤1 − 声明并初始化一个整数数组。
步骤2 − 初始化for循环并检查其长度。
步骤3 − 从索引1开始循环,每次增加2,直到数组的最后一个索引。
步骤4 − 打印数组的元素。
语法
要获取数组的长度(数组中元素的个数),可以使用数组的内置属性 `length`。
以下是其语法:
array.length
其中,`array` 指的是数组引用。
多种方法
我们提供了多种解决方法。
使用静态数组初始化
使用用户自定义方法
让我们逐一查看程序及其输出。
方法一:使用静态数组初始化
示例
在这种方法中,数组元素将在程序中初始化。然后,根据算法,我们需要找到数组中位于奇数位置的元素并打印它们。
public class Main{
//main method
public static void main(String[] args){
//Declare and initialize the array elements
int num[] = {12, 5 , 77, 14, 91, 21, 1};
System.out.println("Odd position of elements present in an array are: ");
//logic implementation
for (int i = 1; i < num.length; i = i+2){
System.out.print(num[i]+" ");
}
}
}
输出
Odd position of elements present in an array are: 5 14 21
方法二:使用用户自定义方法
示例
在这种方法中,数组元素将在程序中初始化。然后,通过将数组作为参数调用用户自定义方法,并在方法内部根据算法找到并打印数组中位于奇数位置的元素。
public class Main{
//main method
public static void main(String[] args){
int num[] = {12, 23, 11, 64, 5, 87, 22, 67, 100};
// calling the user defined method
odd_elements(num);
}
//method body
public static void odd_elements(int []num){
System.out.println("Odd position of elements present in an array are: ");
//logic implementation
for (int i = 1; i < num.length; i = i+2){
System.out.print(num[i]+" ");
}
}
}
输出
Odd position of elements present in an array are: 23 64 87 67
在这篇文章中,我们学习了如何使用Java编程语言打印数组中位于奇数索引位置的元素。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP