使用 C 語言求數字的首位和末位的和


如果我們在 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
",sum); }

輸出

你將看到如下輸出 −

Sum of elements in the array is : 150

更新日期:2021 年 3 月 15 日

4K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始使用
廣告