使用数组和函数来打印C中的前n个元素[就像sort(a + m,a + n)] [英] Use of array and a function to print first n elements in C [as like as sort(a+m, a+n)]
本文介绍了使用数组和函数来打印C中的前n个元素[就像sort(a + m,a + n)]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:我想编写一个函数,以将数组从mth元素打印到第n个元素,其中m <= n,如果a是数组,则函数调用应类似于print(a + m,a + n ).现在,在这种情况下,用户定义的功能应该是什么?
#include <stdio.h>
#include <iostream>
using namespace std;
/* It may be ok or not. If not then what program should write? */
void print(int a[], int n)
{
for(int i=0;; ++i){
if(a[i] == a[n]) break;
printf("%d ",a[i]);
}
}
int main()
{
int a[6] = {1,3,5,6,8,2};
/*We can use to sort this array of 1st n elements*/
sort(a,a+n);
/*if we want to use c function to sort this array 'a' for 1st 4 elements then we write*/
sort(a,a+4);
/*But if we want use to print 1st n elements than what should user defined function looks like?*/
print(a,a+3); //for this function to print 1st 3 elements what should write user defined function
return 0;
}
推荐答案
您可以将指针用于这种格式
You can use pointers for such format
void print (int * begin, int * end){
while(begin != end){
printf("%d", *begin);
begin++;
}
}
这篇关于使用数组和函数来打印C中的前n个元素[就像sort(a + m,a + n)]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文