配列のソートされた個別の要素をC言語で出力します
整数要素の配列が与えられた場合、タスクは重複する値を削除し、ソートされた方法で個別の要素を出力することです。
以下に示すのは、整数型の値を4、6、5、3、4、5、2、8、7、0の形式で格納する配列です。結果は、ソートされた要素を0、2、3、4として出力します。 4、5、5、6、7、8ですが、この結果には重複する値4と5が含まれているため、削除する必要があり、最終結果は0、2、3、4、5、6、7、8になります。
例
Input: array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0}
Output: 0 2 3 4 5 6 7 8 説明
したがって、結果を達成するために
- 個別の要素を取得して、別の配列array1に格納します。
- array1を並べ替えます。
- array1の値を出力します。
アルゴリズム
START STEP 1: DECLARE VARIABLES i, j, array1[size], temp, count = 0 STEP 2: LOOP FOR i = 0 AND i < size AND i++ LOOP FOR j = i+1 AND j < size AND j++ IF array[i] == array[j]) then, break END IF END FOR IF j == size then, ASSIGN array1[count++] WITH array[i] END IF END FOR STEP 3: LOOP FOR i = 0 AND i < count-1 AND i++ LOOP FOR j = i+1 AND j < count AND j++ IF array1[i]>array1[j] then, SWAP array1[i] AND array[j] END IF END FOR END FOR STEP 4: PRINT array1 STOP
例
#include <stdio.h>
/* Prints distinct elements of an array */
void printDistinctElements(int array[], int size) {
int i, j, array1[size], temp, count = 0;
for(i = 0; i < size; i++) {
for(j = i+1; j < size; j++) {
if(array[i] == array[j]) {
/* Duplicate element found */
break;
}
}
/* If j is equal to size, it means we traversed whole
array and didn't found a duplicate of array[i] */
if(j == size) {
array1[count++] = array[i];
}
}
//sorting the array1 where only the distinct values are stored
for ( i = 0; i < count-1; i++) {
for ( j = i+1; j < count; j++) {
if(array1[i]>array1[j]) {
temp = array1[i];
array1[i] = array1[j];
array1[j] = temp;
}
}
}
for ( i = 0; i < count; ++i) {
printf("%d ", array1[i]);
}
}
int main() {
int array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0};
int n = sizeof(array)/sizeof(array[0]);
printDistinctElements(array, n);
return 0;
} 出力
上記のプログラムを実行すると、次の出力が生成されます。
0 2 3 4 5 6 7 8
-
配列要素と印刷要素を動的に合計するCプログラム
数nがあるとします。サイズnの配列を動的に作成し、n個の数値を1つずつ取得して、合計を求める必要があります。配列を作成するには、stdlib.hヘッダーファイル内にあるmalloc()またはcalloc()関数を使用できます。 nの値は、stdinを介した入力としても提供されます。 したがって、入力がn =6で、配列要素が9、8、7、2、4、3の場合、9 + 8 + 7 + 2 + 4 + 3 =33の合計であるため、出力は33になります。 これを解決するには、次の手順に従います- 合計:=0 1つの入力を取り、それをnに保存します arr:=サイズnの配列を動的に作成
-
C言語のポインタを使用して配列要素の合計を計算するにはどうすればよいですか?
ポインタは、他の変数のアドレスを格納する変数です。 次のステートメントを検討してください- int qty = 179; ポインタの宣言 ポインタを宣言するための構文は次のとおりです- int *p; ここで、「p」は他の変数のアドレスを保持するポインタ変数です。 ポインタの初期化 アドレス演算子(&)は、ポインタ変数を初期化するために使用されます。 たとえば、 int qty = 175; int *p; p= &qty; ポインタの配列 これは、アドレスのコレクション(または)ポインターのコレクションです。 宣言 以下は、ポインタの配列の宣言です- dataty