[英]I am unable to get the basic concept in this c program using for loop
This program asks the user for a number of elements and the result tells the frequencies of occurrence of each element.该程序向用户询问一些元素,结果告诉用户每个元素的出现频率。 I have marked the question mark using inline text in the code, please help me, I am unable to get the concept here.
我在代码中使用内联文本标记了问号,请帮助我,我无法在这里理解这个概念。
#include <stdio.h>
int main()
{
int arr[100], freq[100];
int size, i, j, count;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
freq[i] = -1; //?? Why is freq said to be -1???
}
for(i=0; i<size; i++)
{
count=1;
for(j=i+1; j<size; j++)
{
if(arr[i]==arr[j])
{
count++;
freq[j] = 0; //?? How is it checking if some elements going to same as other??
}
}
if(freq[i] != 0)
{
freq[i] = count;
}
}
printf("\nFrequency of all elements of array : \n");
for(i=0; i<size; i++)
{
if(freq[i] != 0)
{
printf("%d occurs %d times\n", arr[i], freq[i]);
}
}
return 0;
}
Please help me.请帮我。
freq[i] = -1;
Here you can assign anything except 0 to overwrite the garbage values present in an array.在这里,您可以分配除 0 以外的任何值来覆盖数组中存在的垃圾值。
Why can't you take 0?为什么不能取0?
if(freq[i] != 0)
{
freq[i] = count;
}
Here you've added this condition where freq[i]
will only be updated if it's not 0. This is to make sure you note the frequencies at the first occurrence of every unique element and at the rest of the occurrences of that particular element freq[i]
will be 0 to avoid printing multiple times in output.在这里,您添加了这种条件,其中
freq[i]
仅在不为 0 时才会更新。这是为了确保您注意每个唯一元素第一次出现时的频率,以及该特定元素freq[i]
出现的 rest freq[i]
为 0 以避免在 output 中多次打印。
freq[j] = 0;
if(freq[i] != 0)
{
printf("%d occurs %d times\n", arr[i], freq[i]);
}
without the above 2 conditions for input,没有上述2个输入条件,
total elements = 5, elements = {1,2,2,1,5}总元素 = 5,元素 = {1,2,2,1,5}
Output: Output:
1 occurs 2 times 1 发生 2 次
2 occurs 2 times 2 出现 2 次
2 occurs 1 times 2 发生 1 次
1 occurs 1 times 1 出现 1 次
5 occurs 1 times 5 出现 1 次
That is not your desired output.那不是您想要的 output。
So to conclude it is pretty straightforward.所以总结起来很简单。 If the element is occurring for the first time at the ith index then only mark update
freq[i]
to its occurrence, and if the same element occurs again at any jth index then make freq[j]
to 0 for the printing purpose.如果元素第一次出现在第 i 个索引处,则仅将 update
freq[i]
标记为其出现,如果相同元素再次出现在任何第 j 个索引处,则将freq[j]
设置为 0 以进行打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.