สามารถคำนวณผลรวมของหลักแรกและหลักสุดท้ายของตัวเลขได้ โดยใช้อัลกอริทึมด้านล่างในภาษา C
อัลกอริทึม
อัลกอริทึมขั้นตอนดังนี้:
START
Step 1: ประกาศตัวแปร no, sum แบบ int
Step 2: อ่านตัวเลขระหว่างรันโปรแกรม
Step 3: คำนวณ sum = no % 10
Step 4: วนลูป while no > 9
no = no / 10
Step 5: คำนวณ sum = sum + no
Step 6: พิมพ์ sum
STOPตัวอย่าง
โปรแกรม C หาผลรวมของหลักแรกและหลักสุดท้ายของตัวเลข:
#include <stdio.h>
int main() {
unsigned int no, sum;
printf("enter any number:");
scanf("%u", &no);
sum = no % 10;
while(no > 9) {
no = no / 10;
}
sum = sum + no;
printf("sum of first and last digit is:%d", sum);
return 0;
}ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:
enter any number: 1242353467 sum of first and last digit is: 8
โปรแกรม C ต่อไปนี้ คำนวณผลรวมทุกสมาชิกในอาร์เรย์:
ตัวอย่าง
#include <stdio.h>
void main() {
// ประกาศอาร์เรย์ - รันไทม์ //
int array[5] = {10, 20, 30, 40, 50};
int i, sum = 0, product = 1;
// อ่านค่าสมาชิกเข้าไปในอาร์เรย์ //
// ลูป for //
for(i = 0; i < 5; i++) {
// คำนวณผลรวมและผลคูณ พิมพ์ผลลัพธ์ //
sum = sum + array[i];
}
// แสดงผลรวม //
printf("Sum of elements in the array is : %d\n", sum);
}ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:
Sum of elements in the array is : 150