Showing posts with label Natural Number. Show all posts
Showing posts with label Natural Number. Show all posts

Give me an integer and I will sum it with the previous natural numbers

How to write a C Program Give me an integer and I will sum it with the previous natural numbers in C Programming Language ?

This C Program Change an Integer Number with Addition of Previous Natural Numbers.
 
Solution:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int geometric_sum (int a);
  4. int main ()
  5. {
  6.     int a = 0, sum = 0;
  7.     printf("Give me an integer and I will sum it with the previous natural numbers : ");
  8.     scanf("%d", &a);
  9.     sum = geometric_sum(a);
  10.     printf("Result: %d", sum);
  11. }
  12.  
  13. int geometric_sum (int a)
  14. {
  15.     if (a == 0)
  16.     {
  17.         printf("Base case!\n");
  18.         return a;
  19.     }
  20.  
  21.     else
  22.     {
  23.         printf("1: sum (%d)\n", a);
  24.         return a + geometric_sum(a-1);
  25.     }
  26.  
  27. }

C Program That in a Given Natural Number x Insert Figure c at Position p

How to Write a program that in a given natural number x insert figure c at position p . The numbers x , c and p are entered from standard input . 


For example , x = 140 , c = 2 , p = 2 , the result is the 1420th


Solution:
  1. #include<stdio.h>
  2. #include<math.h>

  3. int main() {
  4.         int x,c,p,i,y,d;
  5.         scanf("%d%d%d", &x,&c,&p);
  6.         printf("Number: %d, figure %d, required position: %d\n", x,c,p);
  7.         i=1;   
  8.         y=10;  
  9.         if(i==p){
  10.                 x=x*10;
  11.                 x=x+c;
  12.                 printf("X: %d\n", x);
  13.         }
  14.         while(i<p){
  15.         i++;
  16.         c=c*10;
  17.                 if(i==p){
  18.                 d=x%y;
  19.                 x=x-d;
  20.                 x=x*y;
  21.                 x=x+c+d;
  22.                 printf("X: %d\n", x);  
  23.                 }
  24.         y=10*y;
  25.         }
  26.                
  27.  
  28.         return 0;
  29. }