Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it
Showing posts with label function_in_c. Show all posts
Showing posts with label function_in_c. Show all posts

21 Jan 2024

C program that uses a loop to calculate the factorial of a given number

// Factorial program using function


#include <stdio.h>

// Function prototype

long long calculateFactorial(int n);

int main() {

    int number;
    // Get input from the user

    printf("Enter a non-negative integer: ");
    scanf("%d", &number);

    // Check if the input is non-negative

    if (number < 0) {
        printf("Please enter a non-negative integer.\n");
        return 1; // Return with an error code
   }

    // Calculate and display the factorial using a loop

    long long factorial = calculateFactorial(number);
    printf("Factorial of %d = %lld\n", number, factorial);
    return 0;

}

// Function to calculate factorial using a loop

long long calculateFactorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
         long long result = 1;
        for (int i = 2; i <= n; ++i) {
           result *= i;
        }
        return result;
    }
}


14 Jan 2024

C program example that uses functions - This program calculates the sum of two numbers using separate functions for input, addition, and output.


#include <stdio.h>

// Function prototypes
    int getInput();
    int addNumbers(int num1, int num2);
    void displayResult(int result);

int main() {
    // Get input from the user
    int number1 = getInput();
    int number2 = getInput();

    // Perform addition
    int sum = addNumbers(number1, number2);

    // Display the result
    displayResult(sum);
    return 0;
}


// Function to get input from the user
    int getInput() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    return num;
}

// Function to add two numbers
    int addNumbers(int num1, int num2) {
    return num1 + num2;
}

// Function to display the result
    void displayResult(int result) {
    printf("The sum is: %d\n", result);
}


30 Jul 2014

CALL BY VALUE PROGRAM IN C

Program of Call by value for swapping two values

#include<stdio.h>
void swap(int a, int b)
{
  int temp;
  temp=a;
  a=b;
  b=temp;
 }
void main()
{
   int a=5;
   int b=10;
   /*printf("c-programcodes.blogspot.in");*/
   swap(a,b);  /*the values goes out of scope  after the function is executed*/
   printf("values are not swapped");
   printf("a=%d\n",a);
   printf("b=%d",b)
}
==OUTPUT==

values are not swapped
a=5
b=10