C Programming

Function in C Programming

A function is a block of code or we can say a group of statement that performs a particular well defined task. Till now we are familiar with the main() function, and it is mandatory to have the main() function in every program.

Syntax:

return_type function_name( function_parameter ) {
   --------------------
body of the
function
--------------------
}

Advantages of using functions:

  1. When some specific code is to be used more than once and at different places, the use of function avoids the repetition of that code.
  2. The functions can be written once and called at different places of a program.
  3. If we use functions in a program then the program becomes easily understandable, modifiable and easy to run and debug.

C programs have two types of functions:

1. Library Functions

2. User Defied Functions

So, let’s go ahead and try to understand what is Library and User Defined Functions in C Programming…

1. Library Functions:

C has the facility to provide library functions for performing some operations. These functions are present in the C library and they are predefined.

For example, sqrt() is a mathematical library function which is used for finding out the square root of any number. The functions printf() and scanf() are output and input library functions.

To use a library function we have to include the corresponding header file using the preprocessor directive #include.

For example, to use printf() and scanf() we have to include stdio.h preprocessor directive.

Example of Library function in c:

#include <stdio.h>
#include <math.h>
int main()
{
   float num, root;
   printf("Enter a number: ");
   scanf("%f", &num);
   root = sqrt(num);
   printf("Square root of %.2f = %.2f", num, root);
   return 0;
}
                                      C Preprocessor Directives
<assert.h>Program assertion functions
<ctype.h>Character type functions
<locale.h>Localization functions
<math.h>Mathematics functions
<setjmp.h>Jump functions
<signal.h>Signal handling functions
<stdarg.h>Variable arguments handling functions
<stdio.h>Standard Input/Output functions
<stdlib.h>Standard Utility functions
<string.h>String handling functions
<time.h>Date time functions

2. User Defined Functions:

Programmers can create their own functions for performing any specific task of the program. These functions are called user defined functions. To create and use these functions, we should know the following things…

  • Function declaration
  • Function definition
  • Function call
  • Function Declaration:

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

Syntax:

return_type function_name( parameter list );
  • Function Definition:

A function definition defines the definition of a declared function in the program. That means in this part the programmer include the body of the function.

Syntax:

return_type function_name( parameter list ) {
   body of the function
}
  • Function Call:

When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

Example:

#include <stdio.h>
int addition(int num1, int num2)  //function_declaration

int main()
{
int addition(int num1, int num2) //function_definition
{
int sum;
sum
= num1+num2;
return sum;
}
int var1, var2; printf("Enter number 1: "); scanf("%d",&var1); printf("Enter number 2: "); scanf("%d",&var2); int res = addition(var1, var2); //function_call printf ("Result: %d", res); return 0; }

Array in C Programming

Arrays are widely used data type in C language. It is a collection of elements of similar data type. These similar elements could be of all integers, all floats or all characters. An array of character is called as string whereas and array of integer or float is simply called as an array. So array may be defined as a group of elements that share a common name and that are defined by position or index. The elements of an arrays are store in sequential order in memory.

There are mainly two types of Arrays are used:

  • One dimensional Array
  • Multidimensional Array
One Dimensional Array:

So far, we’ve been declaring simple variables: the declaration

                    int i;

declares a single variable, named i, of type int. It is also possible to declare an array of several elements. The declaration

                 int a[10];

declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an array is a variable that can hold more than one value. You specify which of the several values you’re referring to at any given time by using a numeric subscript. (Arrays in programming are similar to vectors or matrices in mathematics.) We can represent the array a above with a picture like this:

 programming C

In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9. The subscript which specifies a single element of an array is simply an integer expression in square brackets. The first element of the array is a[0], the second element is a[1], etc. You can use these “array subscript expressions” anywhere you can use the name of a simple variable, for example:

                a[0] = 10;

Example:

#include <stdio.h>
int main()
{
     int marks[10], i, n, sum = 0, average;
     printf("Enter n: ");
     scanf("%d", &n);
     for(i=0; i<n; ++i)
     {
          printf("Enter number%d: ",i+1);
          scanf("%d", &marks[i]);
          sum += marks[i];
     }
     average = sum/n;
     printf("Average = %d", average);
     return 0;
}
Multi Dimensional Array:

C allows for arrays of two or more dimensions. A two-dimensional (2D) array is an array of arrays. A three-dimensional (3D) array is an array of arrays of arrays.

In C programming an array can have two, three, or even ten or more dimensions. The maximum dimensions a C program can have depends on which compiler is being used.

More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding.

For example

int a[2][4][6];

Matrix Addition Program in C:
#include <stdio.h>
int main(){
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;
    printf("Enter number of rows (between 1 and 100): ");
    scanf("%d", &r);
    printf("Enter number of columns (between 1 and 100): ");
    scanf("%d", &c);
    printf("\nEnter elements of 1st matrix:\n");
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            printf("Enter element a%d%d: ",i+1,j+1);
            scanf("%d",&a[i][j]);
        }
    printf("Enter elements of 2nd matrix:\n");
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            printf("Enter element a%d%d: ",i+1, j+1);
            scanf("%d", &b[i][j]);
        }
    // Adding Two matrices
    for(i=0;i<r;++i)
        for(j=0;j<c;++j)
        {
            sum[i][j]=a[i][j]+b[i][j];
        }
    // Displaying the result
    printf("\nSum of two matrix is: \n\n");
    for(i=0;i<r;++i)
        for(j=0;j<c;++j)
        {
            printf("%d   ",sum[i][j]);
            if(j==c-1)
            {
                printf("\n\n");
            }
        }   
    return 0;
}

String in C Programming

String are the combination of number of characters these are used to store any word in any variable of constant. A string is an array of character. It is internally represented in system by using ASCII value. Every single character can have its own ASCII value in the system. A character string is stored in one array of character type.

e.g. “Ram” contains ASCII value per location, when we are using strings and then these strings are always terminated by character ‘\0’. We use conversion specifies %s to set any string we can have any string as follows:-

char nm [25].

When we store any value in nm variable then it can hold only 24 character because at the end of the string one character is consumed automatically by ‘\0’.

#include<string.h>

There are some common inbuilt functions to manipulation on string in string.h file. these are as follows:

  1. strlen – string length
  2. strcpy – string copy
  3. strcmp – string compare
  4. strups – string upper
  5. strlwrr- string lower
  6. strcat – string concatenate

Example:

#include <stdio.h>

int main() {
   char str[] = "Hello World";

   printf("%s\n", str);

   return 0;
}

Pointer in C Programming

a pointer is a variable that points to or references a memory location in which data is stored. In the computer, each memory cell has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

Pointer declaration:

A pointer is a variable that contains the memory location of another variable in which data is stored. Using pointer, you start by specifying the type of data stored in the location. The asterisk helps to tell the compiler that you are creating a pointer variable. Finally you have to give the name of the variable. The syntax is as shown below.

type * variable name

The following example illustrate the declaration of pointer variable :

int *ptr;
float *string;

Address operator:

Once we declare a pointer variable then we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:

ptr=#

The above code tells that the address where num is stores into the variable ptr. The variable ptr has the value 21260,if num is stored in memory 21260 address then

The following program illustrate the pointer declaration :

/* A program to illustrate pointer declaration*/

main()
{
int *ptr;
int sum;
sum=45;
ptr=&ptr;
printf (”\n Sum is %d\n”, sum);
printf (”\n The sum pointer is %d”, ptr);
}

Pointer expressions & pointer arithmetic:

In expressions, like other variables pointer variables can be used. For example if p1 and p2 are properly initialized and declared pointers, then the following statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* – *p2/p1;
*p2= *p2 + 10;

C allows us to subtract integers to or add integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with pointers p1+=; sum+=*p2; etc., By using relational operators, we can also compare pointers like the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

Structure and Union in C

Structure and Union both are the user defined data type in C language. They allow the programmer to work with different data types at a time.

The main difference between them is:

The size of structure is greater than or equal to the sum of the sizes of its members.

But the size of union is equal to the size of its largest member.

Defining a structure:

A structure is defining by a struct keyword.

Syntax:

struct structure name {

   member definition;
....
.... } [structure variables];
Accessing Structure Members:

In order to access a structure member from outside of the structure we have to use .(dot) operator.

Example:

#include<stdio.h>
#include<string.h>

struct employee
{
    char name[20];
    int age;
};

int main()
{
    struct employee e1;
    e1.age = 24;
    strcpy(e1.name, "Tanmoy");
    printf("Name of Employee 1: %s\n", e1.name);
    printf("Age of Employee 1: %d", e1.age);
    
    return 0;
}
Defining an Union:

Union is defined by the union keyword.

union union-name 
{
member definition
;
....

....
} [union variables];
Accessing Union Members:

Union members are also accessed by using .(dot) operator.

Example:

#include <stdio.h>

union data
{
    int a;
    float b;
    char c;
};
int main( )
{
    union data d;
    d.a = 34;
    d.b = 5.7;
    d.c = 't';
    printf("%d\n", d.a);
    printf("%f\n", d.b);
    printf("%c", d.c);
    
    return 0;
}

6
Leave a Reply

avatar
3 Comment threads
3 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
Joya RivardQueenie MaronaTanmoylow vision glasses Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
low vision glasses
Guest

It is possible to undoubtedly see your knowledge inside the artwork you are writing. The earth wants much more zealous internet writers such as you which may not be scared post how they believe that. Constantly comply with the soul.. low vision glasses

Queenie Marona
Guest

I am commenting to make you understand what a cool experience my wife’s daughter developed checking your webblog. She came to understand so many issues, including what it is like to have an amazing coaching mood to make other individuals with no trouble gain knowledge of certain complicated things. You truly exceeded my desires. Many thanks for displaying these insightful, trustworthy, educational and even cool thoughts on your topic to Gloria.

Joya Rivard
Guest

I like the helpful info you provide in your articles. I will bookmark your weblog and check again here regularly.