Author: admin

  • User Defined Function in C

    In this tutorial, we will learn abt the user-defined function in C programming language. Let us start by understanding what is user-defined function in C.

    A function refers to a block of code that performs a specific task.

    User-defined functions are the ones that are defined by the users according to their needs and they perform the task assigned by the users.

    Let us say that you want to calculate the area of a circle and also find the circumference of that circle, you can do so by creating two different functions and pass the radius value to those functions. The two functions could be:

    • circleArea()
    • cricleCircumference()

    Example of a simple C user-defined function. The program has a separate function to perform the addition of two numbers.

    #include <stdio.h>
    
    // function prototype
    int addFunction(int x, int y);
    
    int main()
    {
      int num1, num2, result;
    
      printf("Enters the first number: ");
      scanf("%d", &num1);
    
      printf("Enters the second number: ");
      scanf("%d", &num2);
    
      result = addFunction(num1, num2);   // function call
      printf("Result: %d", result);
    
      return 0;
    }
    
    int addFunction(int x, int y)	// function definition   
    {
      int sum;
      sum = x + y;
      return sum;	// return statement
    }

    Output:

    Enters the first number: 5
    Enters the second number: 8
    Result: 13

    Considering the above example, let us go through the following topics:

    • function prototype/declaration
    • function definition
    • function call
    • return statement

    Function Prototype

    Declaration of user-defined function in C.

    A function prototype in C is simply a declaration of a function before the main function that does not contain the body of the function. It only specifies the name of the function, its parameter, and the return type of the function.

    Syntax of function prototype:

    return_type function_name(data_type argument1, data_type argument2, ...);

    This line in a program alerts the compiler that the function may be used later in the program.

    In the above program, int addFunction(int x, int y); is the function prototype.

    Note: Also note that, if you defined the function before the main function then the separate function declaration is not required in a program else you need to mention the declaration. Example: In the syntax below, a declaration is not required

    #include <stdio.h>
    
    //user-defined function
    int sum(int a, int b = 5)
    {
    
       ...........
       ...........
    
     
       return result;
    }
    
    //Main function
    int main()
    {
       .............
       .............
    
       // calling a function
       result = sum(a, b);
       ............
       .............
    
       return 0;
    }

    Function Definition

    Defining a function in C: It is the expansion of function declaration or prototype. It contains the codes within the curly braces {} that perform some specific task.

    How to define functions in c:

    return_type function_name( parameter_list ) {
       body of the function;
    }

    Explanation of the above syntax:

    • Return type: A function may return a value unless it is a void function, which does not return any type of value. return_type is a data type of the function. It could return arithmetic values (int, float, etc.), pointers, structures, etc.
    • Function name: Function name refers to identifiers through which function can be identified uniquely. It is a function’s name that is stated to function by following some naming rules.
    • Parameter list: Parameter is also referred to as Argument. We can pass the values through the parameter when the function is invoked. The parameter list refers to the type, order, and number of the parameters of a function
    • Function Body: The function body is enclosed within the curly braces'{}’. It defines the task of a method within the curly braces.

    Example:

    /* function that returns the minimum value
    between two number passed*/
    
    int min(int num1, int num2) 
    {
       int finalValue;
     
       if (num1 > num2)
          finalValue = num1;
       else
          finalValue = num2;
     
       return finalValue;
      //return_type is int
    }

    Function Call

    We call the function by its name and pass the argument(if any) where we want to execute that function. The syntax for calling a function:

    function_name(argument_list);

    In the above program, result = addFunction(num1, num2);is the function call.


    Passing arguments to a function

    In C programming, most of the time we create a function or declare a function that takes and arguments. We call the function by passing a value or more than one value that is referred to as an argument.

    These arguments are the variable that is passed while calling a function.

    In the example above, result = addFunction(num1, num2); is the function call and num1 and num2 are the argument that are passed.


    Return statement

    The return statement in the function is used to terminate the function and return the value to the program line where it is called. The execution control is transferred to the calling function in the program.

    Syntax:

    return (expression);

    In the above program, return sum; is the return statement of the user defined function.

    However, a function can also be called without passing an argument.


    Go through the C program below to practice user defined functions programs in C and also learn how to pass an argument in a function.


  • Sunny Number Program in C

    Let us go through a C program to check whether the number is Sunny Number or Not.

    What is Sunny Number?

    A number N is said to be a sunny number if the number next to the given number (N+1) is a perfect square.

    Example: Let us take a Number 8, then the next number is 8+1=9 and as 3 is a square root of 9, hence 8 is a sunny Number.

    Another example, let the number be 5, then 5+1=6, that has no square roots, hence 5 is not a sunny Number.


    Program to check whether the number is Sunny Number or Not.

    #include <stdio.h>
    #include <math.h>
    #include <stdbool.h >	//for the use of boolean type
    
    bool is_sunny(int);
    
    int main(void)
    {
      int n;
      printf("Enter the number: ");
      scanf("%d", &n);
    
      if (is_sunny(n))
        printf("%d is a sunny number.", n);
      else
        printf("%d is not a sunny number.", n);
    
      return 0;
    
    }
    
    bool is_sunny(int n)
    {
      int square = sqrt(n + 1);
    
      return (square *square == n);
    }

    Output:

    Enter the number: 16
    16 is a sunny number.


    Display all the sunny number within a range of 0 to 100 in C programming

    #include <stdio.h>
    #include <math.h>
    #include <stdbool.h >	//for the use of boolean type
    
    bool is_sunny(int);
    
    int main(void)
    {
      int n;
    
      printf("List of sunny number from 0 to 100 range: \n");
      for (n = 0; n < 100; ++n)
      {
        if (is_sunny(n))
          printf("%d\n", n);
      }
    
      return 0;
    
    }
    
    bool is_sunny(int n)
    {
      int square = sqrt(n + 1);
    
      return (square *square == n);
    }

    Output:

    List of sunny number from 0 to 100 range:
    1
    4
    9
    16
    25
    36
    49
    64
    81


  • Sunny Number Program in C++

    In this tutorial, we will write a C++ program to check for sunny numbers.

    What is Sunny Number?

    A number N is said to be a sunny number if the number next to the given number (N+1) is a perfect square.

    Example: Let us take a Number 8, then the next number is 8+1=9 and as 3 is a square root of 9, hence 8 is a sunny Number.

    Another example, let the number be 5, then 5+1=6, that has no square roots, hence 5 is not a sunny Number.


    Sunny Number Program in C++

    Question: Check if the given number is a sunny number or not in C++ programming.

    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    bool is_sunny(int);   //function prototype
    
    int main()
    {
      int num;
    
      cout << "Enter the number: ";
      cin >> num;
    
      if (is_sunny(num))
        cout << num << " is a sunny number";
      else
        cout << num << " is NOT a sunny number";
    
      return 0;
    }
    
    bool is_sunny(int n)
    {
      // find the square root
      int square = sqrt(n + 1);
    
      return (square *square == n);
    }

    Output:

    Enter the number: 81
    81 is a sunny number


  • Happy Number Program in C

    In this tutorial, we will write a C program to check if the number is happy number or not. Let us start by defining a happy number.

    Happy Number

    A number is said to be a happy number if it yields 1 after a few steps and each step is the sum of the squares of the digits of its results. The sum of the squares starts with the given number and till it reaches one.

    Follow the diagram below:

    happy number
    Happy Number

    Explanation: In the above diagram input is 19. Then the digits 1 and 9 are squared which gives the result 82. After that, the digits 8 and 2 are squared and yield the results 68 and this continues till the final result is 1. And then we can say that 19 is a happy number, if not then it is not a happy number.


    Happy Number Program in C

    #include <stdio.h>
    
    int happyNumber(int);
    
    int main()
    {
      int num = 82;
    
      printf("Enter the number: ");
      scanf("%d", &num);
    
      int temp = num;
    
      while (temp != 1 && temp != 4)
      {
        temp = happyNumber(temp);
      }
    
      //check for 1    
      if (temp == 1)
        printf("%d is a happy number", num);
      else if (temp == 4)
        printf("%d is NOT a happy number", num);
    
      return 0;
    }
    
    //user defined function
    int happyNumber(int num)
    {
      int rem = 0, sum = 0;
    
      //Calculation    
      while (num > 0)
      {
        rem = num % 10;
        sum = sum + (rem *rem);
        num /= 10;
      }
    
      return sum;
    }

    Output:

    Enter the number: 32
    32 is a happy number


  • Happy Number Program in C++

    In this tutorial, we will write a C++ program to check happy number. Let us start by defining a happy number.

    Happy Number

    A number is said to be a happy number if it yields 1 after a few steps and each step is the sum of the squares of the digits of its results. The sum of the squares starts with the given number and till it reaches one.

    Follow the diagram below:

    happy number
    Happy Number

    Explanation: In the above diagram input is 19. Then the digits 1 and 9 are squared which gives the result 82. After that, the digits 8 and 2 are squared and yield the results 68 and this continues till the final result is 1. And then we can say that 19 is a happy number, if not then it is not a happy number.


    Happy Number Program in C++

    Question: C++ program to check whether a number is happy or not using function

    #include <iostream>
    using namespace std;
    
    //Calculation
    int check(int num)
    {
      int rem = 0, sum = 0;
      while (num > 0)
      {
        rem = num % 10;
        sum = sum + (rem *rem);
        num /= 10;
      }
    
      return sum;
    }
    
    //Function to check
    void isHappyNumber(int num)
    {
      int result = num;
      while (result != 1 && result != 4)
      {
        result = check(result);
      }
    
      if (result == 1)
        cout << num << " is a happy number";
      else
      if (result == 4)
        cout << num << " is NOT a happy number";
    }
    
    //Drive function
    int main()
    {
      int num;
    
      cout << "Enter the number: ";
      cin >> num;
    
      isHappyNumber(num);
      return 0;
    }

    Output:

    Enter the number: 15
    15 is not a happy number

    //Another Execution
    Enter the number: 32
    32 is a happy number


  • Automorphic Number program in C++

    In this article, we will write a C++ Program for Automorphic Number. The following C++ programming topic is used in the program below.

    A number is said to be an automorphic number if the square of the given number ends with the same digits as the number itself. Example: 25, 76, 376, etc.

    Automorphic Number

    Automorphic Number Program in C++

    The C++ program to check automorphic number below takes the number from the user as input and checks accordingly.

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int num, flag = 0, sqr;
    
      //user input
      cout << "Enter the number: ";
      cin >> num;
    
      sqr = num * num;
      int temp = num;
    
      //calculation
      while (temp > 0)
      {
        if (temp % 10 != sqr % 10)
        {
          flag = 1;
          break;
        }
    
        temp /= 10;
        sqr /= 10;
      }
    
      if (flag == 1)
        cout << num << ": Not an Automorphic number.";
      else
        cout << num << ": Automorphic number.";
      return 0;
    }

    Output:

    Enter the number: 25
    25: Automorphic number.

    //second execution
    Enter the number: 95
    95: Not an Automorphic number.


  • Automorphic Number Program in C

    In this article, we will write a C Program for Automorphic Number. The following C programming topic is used in the program below.

    A number is said to be an automorphic number if the square of the given number ends with the same digits as the number itself. Example: 25, 76, 376, etc.

    Automorphic Number

    Automorphic Number Program in C

    The C program to check automorphic number below takes the number from the user as input and checks accordingly.

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int main()
    {
      int num;
      printf("Enter the number: ");
      scanf("%d", &num);
    
      int sqr, temp, last;
      int count = 0;
    
      sqr = num * num;
      temp = num;
    
      //Counting digits
      while (temp > 0)
      {
        count++;
        temp = temp / 10;
      }
    
      //calculation
      int den = floor(pow(10, count));
      last = sqr % den;
    
      //display
      if (last == num)
        printf("%d is an Automorphic number.", num);
      else
        printf("%d Not Automorphic number.", num);
    
      return 0;
    }

    Output:

    Enter the number: 25
    25 is an Automorphic number.


  • C Program to Reverse a Number using for loop

    In this tutorial, we will write a reverse number in C using for loop. Before that, you may go through the following topics in C.


    C program to reverse a number using for loop

    This is a reverse number program in C using for loop where the program takes the input from the user. And then iterating through for loop, the program calculates the reverse of a number and then finally displays the result.

    #include <stdio.h>
    
    int main()
    {
      int num, rev = 0, rem;
    
      //User Input
      printf("Enter the Number: ");
      scanf("%d", &num);
    
      for (; num != 0; num = num / 10)
      {
        rem = num % 10;
        rev = rev *10 + rem;
      }
    
      printf("Reversed number: %d", rev);
      return 0;
    }

    Output:

    Enter the Number: 1234
    Reversed number: 4321

    As you can see the initialization part in for loop is left empty and only the condition checking and increment/decrement is filled within “()” in reverse number in c using for loop.


  • C Program to Find the Frequency of Characters in a String

    Here, we will write a C program to find the occurrence of a character in a string. Before that, you may go through the following topic in C.

    We will look at two examples to calculate the frequency of characters in a string.

    1. For a particular character.
    2. For all the character in a string

    C Program to Find the Frequency of Characters in a String (for a particular character)

    Both the string and the character whose frequency needed to be found are entered by the user.

    The questions: write a program in C to find the frequency of any given character in a given string

    #include <stdio.h>
    
    int main()
    {
      char str[100], ch;
      int count = 0, i;
    
      printf("Enter the string: ");
      fgets(str, sizeof(str), stdin);
    
      printf("Enter a character whose frequency is to be found: ");
      scanf("%c", &ch);
    
      for (i = 0; str[i] != '\0'; ++i)
      {
        if (ch == str[i])
          ++count;
      }
    
      printf("\nFrequency of %c = %d", ch, count);
      return 0;
    }

    Output:

    Enter the string: This is simple2code.com
    Enter a character whose frequency is to be found: i

    Frequency of i = 3


    C Program to Find the Frequency of Characters in a String (for all the characters)

    The user needs to enter the string and the number of occurrences for each character will be displayed.

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      char str[100], ch;
      int i, j, k, len, count = 0;
    
      printf("Enter the string: ");
      scanf("%s", str);
    
      len = strlen(str);
    
      for (i = 0; i < len; i++)
      {
        ch = str[i];
        for (j = 0; j < len; j++)
        {
          if (ch == str[j])
          {
            count++;
            for (k = j; k < (len - 1); k++)
              str[k] = str[k + 1];
    
            len--;
            str[len] = '\0';
            j--;
          }
        }
    
        printf("Frequency of %c = %d\n", ch, count);
        count = 0;
        i--;
      }
    
      return 0;
    }

    Output:

    Enter the string: simple2code.com
    Frequency of s = 1
    Frequency of i = 1
    Frequency of m = 2
    Frequency of p = 1
    Frequency of l = 1
    Frequency of e = 2
    Frequency of 2 = 1
    Frequency of c = 2
    Frequency of o = 2
    Frequency of d = 1
    Frequency of . = 1


  • C Program to Convert Uppercase to Lowercase and Vice Versa in a string

    In this tutorial, we will learn to write a C program to convert uppercase to lowercase and vice versa. Before that, you may go through the following topic in C.


    C Program to Convert Uppercase String to Lowercase String

    Explanation: The program asks the user to enter a string. The string can be fully uppercase or partially uppercase. The program converts that string to a fully uppercase string.

    We have used for loop to iterate through the string and also, we know that a is equal to 97 and A is equal to 65 (97-32).

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      char str[25];
      int i;
      printf("Enter the string: ");
      scanf("%s", str);
    
      for (i = 0; i <= strlen(str); i++)
      {
        if (str[i] >= 65 && str[i] <= 90)
          str[i] = str[i] + 32;
      }
    
      printf("Conversion to Lower Case String: %s", str);
      return 0;
    }

    Output:

    Enter the string: sIMpLe2CoDE
    Conversion to Lower Case String: simple2code


    C Program to Convert Lowercase String to Uppercase String

    Explanation: The program asks the user to enter a string. The string can be fully lowercase or partially lowercase. The program converts that string to a fully lowercase string.

    We have used for loop to iterate through the string and also, we know that A is equal to 65 and a is equal to 97 (65+32).

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      char str[25];
      int i;
      printf("Enter the string: ");
      scanf("%s", str);
    
      for (i = 0; i <= strlen(str); i++)
      {
        if (str[i] >= 97 && str[i] <= 122)
          str[i] = str[i] - 32;
      }
    
      printf("Conversion to uppercase String: %s", str);
      return 0;
    }

    Output:

    Enter the string: simPle2Code.com
    Conversion to Uppercase String: SIMPLE2CODE.COM