ผลรวมของหลักแรกและหลักสุดท้ายของตัวเลขสามารถคำนวณได้หากเราใช้อัลกอริธึมที่กล่าวถึงด้านล่างในภาษาการเขียนโปรแกรม C
อัลกอริทึม
อ้างถึงอัลกอริธึมที่ให้มานี้ -
START Step 1: Declare no, sum variables of type int Step 2: Read a number at runtime Step 3: Compute sum=no%10 Step 4: While loop no>9 No=no/10 Step 5: Compute sum=sum+no; Step 6: Print 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(){
//Declaring the array - run time//
int array[5]={10,20,30,40,50};
int i,sum=0,product=1;
//Reading elements into the array//
//For loop//
for(i=0;i<5;i++){
//Calculating sum and product, printing output//
sum=sum+array[i];
}
//Displaying sum //
printf("Sum of elements in the array is : %d\n",sum);
} ผลลัพธ์
คุณจะเห็นผลลัพธ์ต่อไปนี้ -
Sum of elements in the array is : 150