C code for problem solving




Example: Factorial of a Number

  1. #include
  2. int main()
  3. {
  4. int n, i;
  5. unsigned long long factorial = 1;
  6. printf("Enter an integer: ");
  7. scanf("%d",&n);
  8. // show error if the user enters a negative integer
  9. if (n < 0)
  10. printf("Error! Factorial of a negative number doesn't exist.");
  11. else
  12. {
  13. for(i=1; i<=n; ++i)
  14. {
  15. factorial *= i; // factorial = factorial*i;
  16. }
  17. printf("Factorial of %d = %llu", n, factorial);
  18. }
  19. return 0;
  20. }

Output Enter an integer 4

Factorial of input is 24

Example #1: Check if a Number is Positive or Negative Using if...else

  1. #include
  2. int main()
  3. {
  4. double number;
  5. printf("Enter a number: ");
  6. scanf("%lf", &number);
  7. if (number <= 0.0)
  8. {
  9. if (number == 0.0)
  10. printf("You entered 0.");
  11. else
  12. printf("You entered a negative number.");
  13. }
  14. else
  15. printf("You entered a positive number.");
  16. return 0;
  17. }

You can also solve this problem using nested if else statement.

Example #2: Check if a Number is Positive or Negative Using Nested if...else

  1. #include
  2. int main()
  3. {
  4. double number;
  5. printf("Enter a number: ");
  6. scanf("%lf", &number);
  7. // true if number is less than 0
  8. if (number < 0.0)
  9. printf("You entered a negative number.");
  10. // true if number is greater than 0
  11. else if ( number > 0.0)
  12. printf("You entered a positive number.");
  13. // if both test expression is evaluated to false
  14. else
  15. printf("You entered 0.");
  16. return 0;
  17. }

6 comments:

C code for if &amp; if else statement with diagram

If statement in C programming with example BY er RAVI BHADANA  |  FILED UNDER:  C-PROGRAMMING When we need to execute a block of statements ...