Skip to main content

In this blogging you know about digital world.

Function in C

  Function Function : In C programming, a function is a self-contained block of code that performs a specific task or a set of related tasks. Functions are used to break down a program into smaller, more manageable pieces, making the code more organized, readable, and reusable. C supports various types of functions, including library functions and user-defined functions. Below, I'll describe functions in C with examples and discuss their types. Function Syntax: return_type function_name(parameters) {     // Function body     // Statements to perform a task     return value; // (optional) Return value } Here's a breakdown of the elements: - `return_type`: Specifies the data type of the value the function returns. Use `void` if the function doesn't return anything. - `function_name`: A unique identifier for the function. - `parameters`: Input values that the function can accept (optional). - `function_body`: Conta...

Datatype Programming in C, Data Type

 


In C programming, there are several basic data types, each with its own purpose and storage characteristics. Here, I'll describe these data types with examples:

1. **Integer Types:**

   - `int`: Used for representing whole numbers.

     Example

     int number = 42;

 

   - `short`: Used for smaller whole numbers.

     Example

     short smallNumber = 10;

 

   - `long`: Used for larger whole numbers.

     Example

     long bigNumber = 1234567890L;

    

 

   - `long long` (C99 and later): Used for very large whole numbers.

     Example

     long long veryBigNumber = 1234567890123456LL;

   

 

2. **Floating-Point Types:**

   - `float`: Used for single-precision floating-point numbers.

     Example

     float floatValue = 3.14159;

     ```

 

   - `double`: Used for double-precision floating-point numbers (default choice for floating-point).

     Example

     double doubleValue = 2.71828;

     ```

 

   - `long double`: Used for extended precision floating-point numbers.

     Example

     long double extendedValue = 0.12345678901234567890L;

     ```

 

3. **Character Type:**

   - `char`: Used for storing individual characters.

     Example

     char character = 'A';

     ```

 

4. **Boolean Type (C99 and later):**

   - `_Bool`: Used for representing boolean values.

     Example

     _Bool isTrue = 1; // true

     _Bool isFalse = 0; // false

     ```

 

5. **Enumerated Types (enum):**

   - `enum`: Used for creating a set of named integer constants.

     Example

     enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

     enum Days today = Wednesday;

     

6. **Void Type:**

   - `void`: Typically used as a return type to indicate a function does not return a value.

     Example

     void printMessage() {

         printf("Hello, World!\n");

     }

     ```

 

7. **Derived Types:**

   - Pointers: Used to store memory addresses.

     Example

     int number = 42;

     int* ptr = &number; // pointer to int

     ```

 

   - Arrays: Used to store collections of elements of the same data type.

     Example

     int numbers[5] = {1, 2, 3, 4, 5};

     ```

 

   - Structures: User-defined composite data types.

     Example

     struct Point {

         int x;

         int y;

     };

     struct Point p1 = {10, 20};

     ```

 

   - Unions: Similar to structures but share the same memory location for all members.

     Example

     union Value {

         int integer;

         double floating;

     };

     union Value data;

     data.integer = 42;

     data.floating = 3.14;

     ```

 

8. **Type Modifiers:**

   - `signed` and `unsigned`: Modify integer types to indicate signed (positive and negative) or unsigned (non-negative) numbers.

     Example

     unsigned int positiveNumber = 100;

     ```

 

   - `const`: Used to declare constants.

     Example

     const double pi = 3.14159;

     ```

 

   - `volatile`: Indicates that a variable may be modified by external factors and should not be optimized by the compiler.

     Example

     volatile int sensorValue;

     ```

These are the basic data types in C programming, and they provide the foundation for working with various types of data in C programs.

 

Here Some Example

1. Write a program to find whether a number is positive or negative is discussed here. Given a number as input, find whether the number is positive or negative.

#include <stdio.h>

int main() {

    double number;

    // Input a number from the user

    printf("Enter a number: ");

    scanf("%lf", &number);

    // Check if the number is positive or negative

    if (number > 0) {

        printf("The number is positive.\n");

    } else if (number < 0) {

        printf("The number is negative.\n");

    } else {

        printf("The number is zero.\n");

    }

    return 0;

}

 

2.  Write a C Program to Find if the given number is either odd or evenwithout using the modulus operator. Even without using the modulus operator, anumber can be checked if it is odd or even.

#include <stdio.h>

int main() {

    int number;

    // Input a number from the user

    printf("Enter an integer: ");

    scanf("%d", &number);

    // Check if the number is odd or even without using modulus operator

    if ((number & 1) == 0) {

        printf("%d is even.\n", number);

    } else {

        printf("%d is odd.\n", number);

    }

    return 0;

}

 

3.    Write a C Program to swap two numbers without using a third variable in C.

#include <stdio.h>

int main() {

    int num1, num2;

    // Input two numbers from the user

    printf("Enter the first number: ");

    scanf("%d", &num1);

    printf("Enter the second number: ");

    scanf("%d", &num2);

    // Swap the numbers without using a third variable

    num1 = num1 + num2;

    num2 = num1 - num2;

    num1 = num1 - num2;

    // Print the swapped numbers

    printf("After swapping:\n");

    printf("First number: %d\n", num1);

    printf("Second number: %d\n", num2);

    return 0;

}

 

4.   Write a C Program to find the area of a circle is discussed here. Area of the circle can be found using the formula, A = Ï€r2 where r is the radius of the circle. When the radius of the circle is known, the area of the circle can be calculated using the formula mentioned.

 

#include <stdio.h>

#include <math.h>

int main() {

    double radius, area;

    // Input the radius of the circle

    printf("Enter the radius of the circle: ");

    scanf("%lf", &radius);

    // Calculate the area of the circle

    area = M_PI * pow(radius, 2);

    // Print the calculated area

    printf("The area of the circle with radius %.2lf is %.2lf\n", radius, area);

    return 0;

}

5.  Write a C Program program to find the LCM of two numbers is discussedhere. Two numbers are obtained as input and the prime factors of both thenumbers are found. The product of the union of prime factors of both numbers gives the LCM of the two numbers.

#include <stdio.h>

 

// Function to calculate the LCM of two numbers

int calculateLCM(int num1, int num2) {

    int i, gcd, lcm;

  

    // Find the greatest common divisor (GCD) using Euclidean algorithm

    for (i = 1; i <= num1 && i <= num2; ++i) {

        if (num1 % i == 0 && num2 % i == 0) {

            gcd = i;

        }

    }

  

    // Calculate LCM using the formula: LCM = (num1 * num2) / GCD

    lcm = (num1 * num2) / gcd;

  

    return lcm;

}

 

int main() {

    int num1, num2;

 

    // Input two numbers from the user

    printf("Enter the first number: ");

    scanf("%d", &num1);

    printf("Enter the second number: ");

    scanf("%d", &num2);

 

    // Calculate and print the LCM

    int lcm = calculateLCM(num1, num2);

    printf("The LCM of %d and %d is %d\n", num1, num2, lcm);

 

    return 0;

}

 

6. Write a C Program to find the GCD of two numbers is discussed here. TheHCF (Highest Common Factor or GCD (Greatest Common Divisor) of two integers isnothing but the largest integer that can exactly divide a given number withoutleaving a remainder.

#include <stdio.h>

 

// Function to calculate the GCD using the Euclidean algorithm

int calculateGCD(int num1, int num2) {

    int temp;

    while (num2 != 0) {

        temp = num2;

        num2 = num1 % num2;

        num1 = temp;

    }

    return num1;

}

 

int main() {

    int num1, num2;

 

    // Input two numbers from the user

    printf("Enter the first number: ");

    scanf("%d", &num1);

    printf("Enter the second number: ");

    scanf("%d", &num2);

 

    // Calculate and print the GCD

    int gcd = calculateGCD(num1, num2);

    printf("The GCD of %d and %d is %d\n", num1, num2, gcd);

 

    return 0;

}

7.  Write a C Program to find the largest among three numbers in C is discussed here. Three numbers are given as input and the greatest number among the three numbers is displayed as output. 


#include <stdio.h>

int main() {

    int num1, num2, num3;

    // Input three numbers from the user

    printf("Enter the first number: ");

    scanf("%d", &num1);

    printf("Enter the second number: ");

    scanf("%d", &num2);

    printf("Enter the third number: ");

    scanf("%d", &num3);

    // Check which number is the largest

    if (num1 >= num2 && num1 >= num3) {

        printf("The largest number is: %d\n", num1);

    } else if (num2 >= num1 && num2 >= num3) {

        printf("The largest number is: %d\n", num2);

    } else {

        printf("The largest number is: %d\n", num3);

    }

    return 0;

}

 

8.  Write a C Program to find the largest among three numbers in C isdiscussed here. Three numbers are given as input and the greatest number amongthe three numbers is displayed as output.

#include <stdio.h>

int main() {

    int num1, num2, num3;

    // Input three numbers from the user

    printf("Enter the first number: ");

    scanf("%d", &num1);

    printf("Enter the second number: ");

    scanf("%d", &num2);

    printf("Enter the third number: ");

    scanf("%d", &num3);

    // Check which number is the largest

    if (num1 >= num2 && num1 >= num3) {

        printf("The largest number is: %d\n", num1);

    } else if (num2 >= num1 && num2 >= num3) {

        printf("The largest number is: %d\n", num2);

    } else {

        printf("The largest number is: %d\n", num3);

    }

 

    return 0;

}

 

9.  Write a C Program to count a number of digits in an integer is discussed here. An integer is given as input and the total number of digits in that integer is displayed as output. Finding the number of digits in an integer can be done using loops, and recursion, and a log-based solution can be also used.

 

#include <stdio.h>

int main() {

    int number, count = 0;

    // Input an integer from the user

    printf("Enter an integer: ");

    scanf("%d", &number);

    // Handle the case of a negative number

    if (number < 0) {

        number = -number; // Make it positive

    }

    // Count the number of digits using a loop

    while (number != 0) {

        number /= 10;

        count++;

    }

    printf("The number of digits in the integer is: %d\n", count);

    return 0;

}

 

10. Write a C Program to find the sum of the digits of the given number is discussed here. This problem can be solved in two methods: The iterative approach and the Recursive approach

You can find the sum of the digits of a given number in C using both an iterative approach and a recursive approach. Here's a C program that demonstrates both methods:

**Iterative Approach:**

 

#include <stdio.h>

int sumOfDigitsIterative(int number) {

    int sum = 0;

    while (number > 0) {

        sum += number % 10; // Add the last digit to the sum

        number /= 10;     // Remove the last digit

    }

    return sum;

}

int main() {

    int num;

    // Input an integer from the user

    printf("Enter an integer: ");

    scanf("%d", &num);

    // Calculate the sum of digits using the iterative approach

    int sum = sumOfDigitsIterative(num);

    printf("The sum of the digits is: %d\n", sum);

    return 0;

}


**Recursive Approach:**


#include <stdio.h>

int sumOfDigitsRecursive(int number) {

    if (number == 0) {

        return 0; // Base case: if the number is 0, the sum is 0

    } else {

        return (number % 10) + sumOfDigitsRecursive(number / 10);

    }

}

int main() {

    int num;

    // Input an integer from the user

    printf("Enter an integer: ");

    scanf("%d", &num);

    // Calculate the sum of digits using the recursive approach

    int sum = sumOfDigitsRecursive(num);

    printf("The sum of the digits is: %d\n", sum);

    return 0;

}

In both programs:

  We include the standard input/output library (`stdio.h`).

• For the iterative approach, we define a function `sumOfDigitsIterative` that takes an integer `number` and calculates the sum of its digits using a `while` loop. In each iteration, we add the last digit to the `sum` and remove the last digit by dividing the number by 10.

• For the recursive approach, we define a function `sumOfDigitsRecursive` that takes an integer `number`. The base case is when the number is 0, and in that case, the function returns 0. Otherwise, it calculates the sum of the last digit and the sum of the digits in the remaining number by recursively calling itself.

  In the `main` function, we input an integer from the user, call the respective function to calculate the sum of its digits, and then print the result.

 You can choose either the iterative or recursive approach to find the sum of the digits of a given number.

11. Write a C Program to find the sum of natural numbers with and withoutrecursion is discussed in this article. A number, N is obtained as input andthe sum of the first N natural numbers is given as output.

You can calculate the sum of the first N natural numbers in C using both recursive and iterative approaches. Here's a C program that demonstrates both methods:

 

**Iterative Approach:**

#include <stdio.h>

int sumOfNaturalNumbersIterative(int n) {

    int sum = 0;

    for (int i = 1; i <= n; i++) {

        sum += i;

    }

    return sum;

}

int main() {

    int n;

    // Input a positive integer from the user

    printf("Enter a positive integer (N): ");

    scanf("%d", &n);

    if (n < 1) {

        printf("Please enter a positive integer.\n");

        return 1; // Exit with an error code

    }

    // Calculate the sum of the first N natural numbers using the iterative approach

    int sum = sumOfNaturalNumbersIterative(n);

    printf("The sum of the first %d natural numbers is: %d\n", n, sum);

    return 0;

}

**Recursive Approach:**

#include <stdio.h>

int sumOfNaturalNumbersRecursive(int n) {

    if (n == 0) {

        return 0; // Base case: The sum of 0 natural numbers is 0

    } else {

        return n + sumOfNaturalNumbersRecursive(n - 1);

    }

}

int main() {

    int n;

    // Input a positive integer from the user

    printf("Enter a positive integer (N): ");

    scanf("%d", &n);

    if (n < 1) {

        printf("Please enter a positive integer.\n");

        return 1; // Exit with an error code

    }

    // Calculate the sum of the first N natural numbers using the recursive approach

    int sum = sumOfNaturalNumbersRecursive(n);

    printf("The sum of the first %d natural numbers is: %d\n", n, sum);

    return 0;

}

 

In both programs:

 

      We include the standard input/output library (`stdio.h`).

• For the iterative approach, we define a function sumOfNaturalNumbersIterative` that takes an integer `n` and calculates the sum of the first N natural numbers using a `for` loop.

• For the recursive approach, we define a function `sumOfNaturalNumbersRecursive` that takes an integer `n`. The base case is when `n` is 0, and in that case, the function returns 0. Otherwise, it calculates the sum of `n` and the sum of the first `n-1` natural numbers by recursively calling itself.

• In the `main` function, we input a positive integer `n` from the user and validate that `n` is positive. Then, we call the respective function to calculate the sum of the first `n` natural numbers and print the result.

You can choose either the iterative or recursive approach to find the sum of the first N natural numbers.


12.  Write a C Program to find the sum of numbers in a given range is discussed here. Given the starting and ending interval, the sum of all the numbers in that range will be displayed as output.

#include <stdio.h>

int main() {

    int start, end;

    int sum = 0;

    // Input the starting and ending intervals from the user

    printf("Enter the starting interval: ");

    scanf("%d", &start);

    printf("Enter the ending interval: ");

    scanf("%d", &end);

 

    // Validate that the starting interval is less than or equal to the ending interval

    if (start > end) {

        printf("Invalid input: The starting interval should be less than or equal to the ending interval.\n");

        return 1; // Exit with an error code

    }

    // Calculate the sum of numbers in the specified range

    for (int i = start; i <= end; i++) {

        sum += i;

    }

    // Print the sum

    printf("The sum of numbers in the range [%d, %d] is: %d\n", start, end, sum);

 

    return 0;

}

 

Comments

Popular Posts