Variable Arguments in C-Language

 

Variable Arguments in  C-Language

Variable Arguments

  • Variable length argument is a feature that allows a function to receive any number of arguments.
  • There are situations where we want a function to handle variable number of arguments according to requirement.
  1.  Sum of given numbers.
  2.  Minimum of given numbers. and many more.
Variable number of arguments are represented by three dotes (…)
Syntax:
    datatype functionname(datatype,...)
    {
    ...
    ...
    }
    
    void main()
    {
    functionname(v1,v2,v3);
    functionname(v1,v2,v3,v4,v5);
    }
/* C Variable Length Arguments - This program
 * demonstrates variable length arguments in C
 */

#include<stdio.h>
#include<stdarg.h>
#include<conio.h>

int avg(int num, ...)
{
	va_list valist;
	int sum = 0;
	int i;

	// initializing valist for num number of arguments
	va_start(valist, num);

	// now accessing all the arguments that is assigned to valist
	for(i=0; i<num; i++)
	{
		sum = sum + va_arg(valist, int);
	}

	// now cleaning the memory reserved for the valist
	va_end(valist);

	return sum/num;
}

void main()
{
	int num1=10, num2=20, num3=30;
	clrscr();

	printf("The average is %d", avg(3, num1, num2, num3));

	getch();
}

Output:
The average is 20




Files In C Language

 

Files In C Language

File : File is a collection of data or information which is used to store the data permanently
Types of files:
1.Text Files
2.Document Files
3.Audio Files
4.Video Files
5.PDF Files ...


File Operations
1.Open or create a file
2.Write the data into the file
3.Read the data from the file
4.close a file
Open file
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
SnoModeDescription
1rOpens an existing text file for reading purpose.
2wOpens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.
3aOpens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
4r+Opens a text file for both reading and writing.
5w+Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
6a+Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
  "rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing File:
int fclose( FILE *fp );
Close a file using fclose( ) function

Writing a File:
fprintf(file,"Data")
fputs("Data",File)
Program:
#include <stdio.h>
#include <conio.h>
void main() {
   FILE *fp;
   fp = fopen("test.txt", "w+");
   fprintf(fp, "This is testing File\n");
   fputs("This is testing File\n", fp);
   fclose(fp);
   printf("Success");
   getch();
}

Reading a File
fscanf(File,"type of data",variable);

fgets(variable,size, FILE)
Program
#include <stdio.h>
#include <conio.h>

void main() {

   FILE *fp;
   char x[255];

   fp = fopen("test.txt", "r");
   fscanf(fp, "%s", x);
   printf("1 : %s\n", x );

   fgets(x, 255, (FILE*)fp);
   printf("2: %s\n", x );
   
   fclose(fp);
   printf("Success");
   getch();

}



Functions in C Language

 

C Functions


Function is a collection of statements used to perform specific operation.In C Language these function are classified into following types
  1. predefined Function
  2. UserDefined Function


PreDefined Functions

    If any function already designed by the C Develophers is known as predefined functions .These are classified into following types
    1. printf()
    2. Scanf()
    3. getch()
    4. clrscr()
    5. sizeof() ...ete

UserDefined Function

If any function designed by the programmer is known as user defined function
Syntax
  returntype functionname(list of paramers/no parameters);    //function Declaration
  returntype functionname(list of paramers/no parameters)      //function Body
  {
  ....
  ....
  ....
  ....
  }
  
in the above syntax first you declare the function.Ofter you declare the function body
These functions are classified into fallowing types
  1. Parametarized Function
  2. NoParametarized Function
  • Parametarized Function:
  • If any function signature contains list of parameters is known as Parametarized Function.
    Syntax
      returntype functionname(datatype variable1,datatype variable2,....);    //function Declaration
      returntype functionname(datatype variable1,datatype variable2,....)      //function Body
      {
      ....
      ....
      ....
      ....
      }
      
  • NoParametarized Function:
  • If any function signature does not contains list of parameters is known as NoParametarized Function.
    Syntax
      returntype functionname();    //function Declaration
      returntype functionname()     //function Body
      {
      ....
      ....
      ....
      ....
      }
      
    Based on the return type these functions are classified into following types
    1. No Returntype With NoParametarized Function
    2. No Returntype With Parametarized Function
    3. Returntype With NoParametarized Function
    4. Returntype With Parametarized Function
  • No Returntype With NoParametarized Function
  • #include<stdio.h>
    #include<conio.h>
    void max();
    void max()
    {
    int x,y;
    printf("Enter x,y values");
    scanf("%d%d",&x,&y);
    if(x>y)
    {
    printf("x is max");
    }
    else
    {
    prinf("y is max");
    }
    };
    void main()
    {
    clrscr();
    max();
    getch();
    }
     


  • No Returntype With Parametarized Function
  • #include<stdio.h>
    #include<conio.h>
    void max(int x,int y);
    void max(int x,int y)
    {
    
    if(x>y)
    {
    printf("x is max");
    }
    else
    {
    prinf("y is max");
    }
    };
    void main()
    {
    clrscr();
    int x,y;
    printf("Enter x,y values");
    scanf("%d%d",&x,&y);
    max(x,y);
    getch();
    }
     


  • Returntype With NoParametarized Function
  • #include<stdio.h>
    #include<conio.h>
    int max();
    int max()
    {
    int x,y;
    printf("Enter x,y values");
    scanf("%d%d",&x,&y);
    if(x>y)
    {
    return x;
    }
    else
    {
    return y;
    }
    };
    void main()
    {
    clrscr();
    printf("%d",max());
    getch();
    }
     


  • Returntype With Parametarized Function
  • #include<stdio.h>
    #include<conio.h>
    int  max(int x,int y);
    int  max(int x,int y)
    {
    
    if(x>y)
    {
    return x;
    }
    else
    {
    return y;
    }
    };
    void main()
    {
    clrscr();
    int x,y;
    printf("Enter x,y values");
    scanf("%d%d",&x,&y);
    printf("%d",max(x,y));
    getch();
    }
     


    Function Calling

    Function Calling Syntax :
    functionname(arguments,...);
    Example: max(10,20)
    Here Max is a functionname
    10,20 are the arguments

    C - Recursion

    The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
    Syntax :
     void recursion() {
       recursion(); /* function calls itself */
    }
    
    int main() {
       recursion();
    }
     
    #include<stdio.h>
    #include<conio.h>
    int factorial(int i) {
    
       if(i <= 1) {
          return 1;
       }
       return i * factorial(i - 1);
    }
    
    void  main() {
       int i = 5;
       printf("Factorial of %d is %d//n", i, factorial(i));
       getch();
    }
    

    Memory Management in C-Language

     

      Memory Management  

    Dynamic Memory Allocation in C

    • The process of allocating memory at runtime is known as dynamic memory allocation.
    • Library routines known as memory management functions are used for allocating and freeing memory during execution of a program.
    • These functions are defined in stdlib.h header file.
    FunctionDescription
    malloc()allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space
    calloc()allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory
    Freereleases previously allocated memory
    reallocmodify the size of previously allocated space

    Memory Allocation Process

    • Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in a memory area called Stack.
    • The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.

    Allocating block of Memory

    • malloc() function is used for allocating block of memory at runtime.
    • This function reserves a block of memory of the given size and returns a pointer of type void.
    • This means that we can assign it to any type of pointer using typecasting.
    • If it fails to allocate enough space as specified, it returns a NULL pointer.
    Syntax:
        void* malloc(byte-size)
    

    calloc()

    • It is another memory allocation function that is used for allocating memory at runtime.
    • calloc function is normally used for allocating memory to derived data types such as arrays and structures.
    • If it fails to allocate enough space as specified, it returns a NULL pointer.
    Syntax:
    void *calloc(number of items, element-size)

    realloc()

    • realloc() changes memory size that is already allocated dynamically to a variable.
    Syntax:
        void* realloc(pointer, new-size)
    




    String Palindrome Program in Python

                      

        String  Palindrome Program in Python

    Examples: 

    Input : malayalam
    Output : Yes
    
    Input : MSK
    Output : No

    Program:

      def checkPalindrome(str):
          return str == str[::-1]
       
       
      # Driver code
      s = "malayalam"
      ans = checkPalindrome(s)
       
      if ans:
          print("Palindrome")
      else:
          print("Not Palindrome")

      OutPut:
      Palindrome

      Area Of Equilateral Triangle In Python

                       

          Area Of Equilateral Triangle In Python

      This is how an equilateral triangle looks like:

      Equilateral Triangle

      As you can see, this is an equilateral triangle with a side length of “a” units and a height of “h” units.

      The altitude of an equilateral triangle cuts the opposite side at right angles. So, by using the Pythagoras theorem, we can calculate the height of an equilateral triangle to be sqrt(3/4)a.

      Thus, the area of an equilateral triangle = 1/2 * sqrt (3/4)a * a

      Area = (sqrt 3)/4 * a^2

      Program:

        import math
        a=float(input("enter side of the triangle: "));
        area=(math.sqrt(3)/4)*a*a;
        print("Area Of Equilateral Triangle ",area);

        OutPut:
        enter side of the triangle: 10
        Area Of Equilateral Triangle  43.301270189221924

        Simple Calculator Program In Python

                        

            Simple Calculator Program In Python


        Program:

          # define functions  
          def add(x, y):  
             
             return x + y 
          def sub(x, y): 
             
             return x - y 
          def mul(x, y): 
             
             return x * y 
          def div(x, y): 
             
             return x / y  
          # take input from the user  
          print("Select operation.")  
          print("1.Addition")  
          print("2.Subtraction")  
          print("3.Multiplication")  
          print("4.Division")  
            
          choice = input("Enter choice(1/2/3/4):")  
            
          num1 = int(input("Enter first number: "))  
          num2 = int(input("Enter second number: "))  
            
          if choice == '1':  
             print(num1,"+",num2,"=", add(num1,num2))  
            
          elif choice == '2':  
             print(num1,"-",num2,"=", sub(num1,num2))  
            
          elif choice == '3':  
             print(num1,"*",num2,"=", mul(num1,num2))  
          elif choice == '4':  
             print(num1,"/",num2,"=", div(num1,num2))  
          else:  
             print("Invalid input")  

          OutPut:
          Select operation.
          1.Addition
          2.Subtraction
          3.Multiplication
          4.Division
          Enter choice(1/2/3/4):2
          Enter first number: 12
          Enter second number: 23
          12 - 23 = -11

          Check whether a number can be expressed as a sum of two prime numbers In Python

                         

              Check whether a number can be expressed as a sum of two prime numbers In Python

          For example, the number 34 is given as input.
          
          34 = 3 + 31
          34 = 5 + 29
          34 = 11 + 23
          34 = 17 + 17

          Program:

            # Python program to check whether a number can be expressed as a sum of two prime numbers

            def prime(n):
                isPrime = 1
                for i in range (2,int(n/2),1):
                    if(n % i == 0):
                        isPrime = 0
                        break
                return isPrime

            n = int(input("Enter a number : "))
            f = 0;
            i = 2
            for i in range (2,int(n/2),1):
                if(prime(i) == 1):
                    if(prime(n-i) == 1):
                        print(n,"can be expressed as the sum of",i,"and",n-i)
                        f = 1;
            if (f == 0):
                print(n,"cannot be expressed as the sum of two prime numbers")

            OutPut:
            Enter a number : 34
            34 can be expressed as the sum of 3 and 31
            34 can be expressed as the sum of 5 and 29
            34 can be expressed as the sum of 11 and 23


            Enter a number : 35
            35 can be expressed as the sum of 4 and 31

            Enter a number : 37
            37 cannot be expressed as the sum of two prime numbers

            replace all 0's with 1 in a given integer In Python

                          

                    Replace all 0's with 1 in a given integer In Python

            Input: 102405

            Output: 112415

            Program:

              # Python program to replace all 0’s with 1 in a given integer

              def re(n):

                  if (n == 0):
                      return 0;



              # Extract the last digit and change it if needed

                  digit = n % 10

                  if (digit == 0):

                      digit = 1
                  return re(int(n/10)) * 10 + digit

              n = int(input("Enter the number : "))

              print("Number after replacement : ",re(n))

              OutPut:
              Enter the number : 123034
              Number after replacement :  123134

              Python program to print the Armstrong numbers between the two intervals

                           

                      Python program to print the Armstrong numbers between the two intervals

              An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153  is an Armstrong

              Program:

                # Python program to print the Armstrong numbers between the two intervals

                import math
                n1 = int(input("Enter start value : "))
                n2 = int(input("Enter end value : "))
                result = 0
                n = 0
                for i in range(n1+1 ,n2,1):
                    t2 = i
                    t1 = i

                    while (t1 != 0):
                        t1 = int(t1/10)
                        n = n + 1

                    while (t2 != 0):
                        remainder = t2 % 10
                        result = result + math.pow(remainder, n)
                        t2 = int(t2/10)

                    if (result == i):
                        print(i)

                    n = 0
                    result = 0

                OutPut:
                Enter start value : 100
                Enter end value : 500
                153
                370
                371
                407


                Enter start value : 200
                Enter end value : 1000
                370
                371
                407

                Prime Number Program in Given Range in Python

                  

                         Prime Number Program in Given Range in Python

                Prime number in C: Prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17, 19, 23.... are the prime numbers.

                factors Program In Python

                            

                        Factors Program In Python


                the factors of number 10 are

                1 * 10 = 10

                2 * 5 = 10

                5* 2 = 10

                10* 1 = 10

                Program:

                  n = int(input("Enter a number : "))
                  count = 0
                  for i in range(1, n+1, 1):
                      if(n % i == 0):
                          count = count + 1
                          print(i, end = " ")
                  print("\nTotal factors of",n," is :",count)

                  OutPut:
                  Enter a number : 10
                  1 2 5 10 
                  Total factors of 10 : 4

                  Enter a number : 20
                  1 2 4 5 10 20 
                  Total factors of 20  is : 6

                  Abundant number In Python

                             

                          Abundant number In Python


                  An abundant number is a number for which the sum of its proper divisors is greater than the

                   number itself.

                  The divisors of 12 are 1, 2, 3, 4 and 6.

                  The sum of divisors of 12 is 16.

                  12 < 16.Hence, 12 is an abundant number.

                  Program:

                    n = int(input("Enter N Value"))
                    sum = 0
                    for i in range(1,n):
                    if(n % i == 0):
                    sum = sum + i
                    if(n < sum):
                    print("It is a Abundant Number")
                    else:
                    print("Not Abundant Number")

                    OutPut:
                    Enter N Value12
                    It is a Abundant Number

                    Enter N Value4
                    Not Abundant Number