Tổng của chữ số đầu tiên và chữ số cuối cùng của một số có thể được tính nếu chúng ta sử dụng thuật toán được đề cập dưới đây trong ngôn ngữ lập trình C.
Thuật toán
Tham khảo một thuật toán được cung cấp kèm theo đây -
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
Ví dụ
Sau đây là chương trình C để tìm tổng của chữ số đầu tiên và chữ số cuối cùng của một số -
#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; }
Đầu ra
Bạn sẽ thấy kết quả sau -
enter any number:1242353467 sum of first and last digit is:8
Sau đây là một chương trình C để tính tổng tất cả các phần tử trong một mảng -
Ví dụ
#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); }
Đầu ra
Bạn sẽ thấy kết quả sau -
Sum of elements in the array is : 150