Category Archives: C Tutorial

C Type Casting

Here you know about type casting is a mechanism in the c programming language that enables a variable of one data type to be converted to another datatype. When a variable is typecasted into a different type, the compiler basically treats the variable as the new data type.

Type of casting

  • implicit or automatic
  • explicit or given

implicit or automatic

An implicit or automatic casting compiler will automatically change one type of data into another. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to afloat.

Example:

Here the value of 'a' has been promoted from short to int and we have not had to specify any type-casting operator. implicit conversions affect fundamental data types. Typecasting should always be used in the right order (low to the higher data type). Typecasting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example, instance truncating afloat when typecasting to an int. This can be avoided with an explicit conversion. Below is the right order for numerical conversion.

short int -> int -> unsigned int ->long int -> unsigned long int -> float -> double -> long double

explicit or given

Casting allows you to make this type of conversion explicit, or to force it when it wouldn’t normally happen. To perform typecasting, put the desired type including modifiers (like double) inside parentheses to the left of the variable or constant you want to cast.

Example:

type casting from char to int results in ASCII code –

 

C Error Handling

For every c program, it is required to have a proper error handling mechanism that can deal with errors that occur at runtime. Error handling is the process of responding to the occurrence of any error that occurs during the computation, of exceptions. In the c programming language, there is no support for error handling and garbage collection, the programmers have to make sure that a program comes out of an error condition gracefully.

In C Programming Language errors can be identified on the basis of return values of function calls, c function return -1 or NULL in case of any error condition and sets an error code for a global variable called errno which indicates an error occurred during any function call. You can find various error codes defined in <error.h> header file. Based on these return values programmer can take proper action to handle the error. The programmer should set errno to zero (0) at the time of initialization of the program. A value of zero(0) indicates that there is no error in the program.

errno, perror() and strerror()

In C Programming Language we have perror() and strerror() functions which can be used to display the text message associated with errno.

  • perror() – It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
  • strerror() – It returns a pointer to the textual representation of the current errno value.
  • stderr – It is a file stream to output the errors.

Let’s take a look at the below example code –

Output:

Preventing divide by zero errors

It is common to mistake for C Programmers do not to take care of is not to check if a divisor is zero prior to any division operation. Let’s take a look at the below snippet of the code which will produce a runtime error and in most cases, exit.

Here is an example of a program in action to handle such condition –

The above program will handle a division by zero condition with the below output :

Output:

Program Exit Status

There are two macros available in C Programming Language that be used when we are exiting a program.

  • EXIT_SUCCESS – This macro is used to indicate the exiting after the successful operation of the program and its value is zero(0)
  • EXIT_FAILURE – This macro is used to indicate the exiting with error condition and value of this macro is -1

Output:

C Recursion

C Recursion

In C programming, recursion is a process where a function calls itself to solve a complex iterative task. The function that calls itself is known as a recursive function. The recursive function calls itself to solve a complex iterative task by dividing it into sub-tasks. In this tutorial, you’ll learn about recursion in C. In particular, you’ll learn:

  • What Is Recursion
  • What Is Recursive Function
  • Working Of Recursive Function
  • Recursion flowchart
  • Characteristics of a Recursive function
  • Advantages Of Recursion
  • Disadvantages Of Recursion

What Is Recursion In C

Recursion is the process where a function calls itself its subroutine in order to solve a complex iterative task by dividing it into sub-tasks. The function that calls itself is known as a recursive function. Any function which calls itself recursively is called a recursive function. The process of calling a function by itself is called recursion. It is an efficient approach to solving a complex mathematical computation task by dividing it into sub-tasks. The approach to solving a problem in recursion is called Divide and Conquer.

Any problem that can be solved recursively, can also be solved iteratively but recursion is considered a more efficient method of programming. It requires the least amount of code to perform some complex tasks using recursion instead of another method. Although recursion is not recommended for all problems, it is best suited for some problems like sorting, searching, Inorder/Preorder/Postorder Tree Traversals, DFS of Graph algorithms. However, recursion must be implemented carefully. Otherwise, it may lead to an infinite loop if no base condition is met that will terminate the function.

What Is Recursive Function

Any function which calls itself recursively is called a recursive function. A recursive function calls itself to solve a complex iterative task by dividing it into sub-tasks. A recursive function repeats itself several times to compute or return the final output. Recursion must be implemented carefully otherwise it may lead to an infinite loop. The recursive function must have a valid terminating condition or base case that will terminate the function. At this point, recursion stops, and the final result is returned from the function.

Syntax Of Recursive Function In C

The general pseudocode representation or syntax of a recursive function in c programming is as follows:

Syntax:-

Characteristics of a recursive function In C

The General Characteristics of a recursive function is as follows:

  • A recursive function is a function that calls itself.
  • The speed of a recursive program is slower because of stack overheads.
  • A recursive function must have terminating conditions and recursive expressions.

Note:- Recursive function must have a valid terminating condition otherwise it leads to an infinite loop.

How does recursion work In C?

To understand how recursion works let’s have one of the popular examples of recursion. In this example, we will calculate the factorial of n numbers. The factorial of n numbers is expressed as a series of repetitive multiplication as shown below:

Suppose we want to find a factorial of 5, then this will be represented as following using recursion:

The flowchart image illustrates the working of recursive function to find factorial of 5 :

c-recursion-flowchart

Here, the recurse() function is a recursive function. It calls itself inside the functional body.

Factorial Program in C Using Recursion

The following factorial program demonstrates the use of the recursive function to find the factorial of a given number using recursion in c programming.

Program:-

Output:-

Suppose the value of i=5, since i is not equal to 1, the statement:

will be executed with i=5 i.e.

As you can see this statement again calls a factorial function with value i-1 which will return the value:

This recursive calling process continues until the value of i is equal to 1. When i is equal to 1 it returns 1 and execution of this function stops. We can review the series of recursive call as follow:

Fibonacci Series In C Using Recursion

The following Fibonacci series program demonstrates the use of the recursive function to generate the Fibonacci series of a given number using recursion in c programming.

Program:-

Output:-

Advantages of Recursion In C

Advantages of recursion are as follows:

  • It requires a few variables which make the program clean.
  • It shortens the complex and nested code.

Disadvantages of Recursion In C

Disadvantages of recursion are as follows:

  • It is hard to debug the recursive functions.
  • It is tough to understand the logic of a recursive function.

C Variable Arguments

In C Programming Language a function usually takes a fixed number of arguments and their data type is also declared therein function declaration, in this scenario we are aware of the number of c variable arguments required, but there are situations come across where the number of arguments is not fixed or not known beforehand when the function is written. The most well-known example would be printf, which takes one required parameter, and may also optionally be passed one or more additional parameters.

Let’s take look at the below example code –

In C Programming Language we can define a function with a variable number of arguments. This can be achieved using three special macros va_start, va_arg & va_end are defined in stdarg. h, to process the variable arguments.

In order to access the c variable argument list, va_start must be called as below –

va_start() is used to initialize pvar to the beginning of the variable argument list. va_start() must be invoked before any access to the unnamed arguments.

The parameter ‘pname’ is the identifier of the rightmost parameter in the variable parameter list in the function definition (the one just before the ellipses ie., “, …”).

After the initialization, we can access the variable argument list via va_arg macro.

pvar is a pointer to the variable argument list, and type is the type name of the next argument to be returned.

va_arg() expands to an expression that has the type and value of the next argument in the call. The parameter pvar must be initialized by va_start(). Each call to this macro will extract the next argument from the argument list as a value of the specified type.

When all the arguments have been processed, the va_end function should be called. This will prevent the va_list supplied from being used any further. The va_end function is declared as

pvar is a pointer to the variable argument list

The va_end() macro is used to clean up. If va_end is not used, the behavior is undefined. The entire argument list can be re-traversed by calling va_start again, after calling va_end.

Example:

 

C Memory Management

Memory management is one of the most fundamental and important aspects of any computer programming language. In many programming languages, you don’t have to worry about memory management, but in C Programming Language you do memory management manually. C is one of the most powerful programming languages. Pointer is one of the most powerful features of the C programming language which gives you the ability to point memory locations. This feature enables easy memory access.

As we all know computer memory is made up of a large number of cells, which are further organized as addressable registers. Each register is responsible to store a sequence of bits. So it is always necessary to manage these memory locations effectively to increase utilization.

Types of memory allocations in C

There are two ways in which memory can be allocated in C

  • Static memory allocation or Compile time allocation
  • Dynamic memory allocation or Run time allocation

Static or compile-time memory allocation

In this method desired memory is allocated at the time of variable declaration or beginning of the program. The amount of memory allocation is fixed and is determined at the time of program compilation.

Example:

when the first statement int a,b; is compiled 4 consecutive bytes(integer occupies 4 bytes in a 32-bit machine) for each variable a,b will be allocated.

Drawbacks of static memory allocation

  • If we declare more number of elements and we are using less number of elements then the memory allocated for the not used variables will be wasted. The unused memory cells are not made available to other applications. This leads to inefficient use of memory.
  • The size of the data type or variable must be known before.
  • We can not change the size of a variable at run time.

Dynamic or Runtime C Memory Allocation

In C Programming Language it is not always possible to predict the memory requirement for the program, so it is better to allocate the memory in real-time whenever required, it makes efficient use of memory.

C Programming Language provides the following dynamic allocation and deallocation functions –

  • malloc()
  • calloc()
  • realloc()
  • free()

malloc,calloc, and realloc are used for memory allocation and deallocation is achieved by the use of the free function.

Allocating A Block of Memory-malloc()

The malloc() function allocates the memory at run time whenever required. It allocates the memory block with the required number of contiguous bytes in the c memory management system and returns the pointer to the first byte(base address) or null if there is some error occur.

Syntax:

Example:

  1. First, we declare a pointer variable ‘p’.
  2. Then the pointer itself is equal to a pointer type int that contains the memory address space for an int.
  3. Size () return the space it occupies what you want, if you put int in, such as 2 bytes, because we have assigned two bytes.
  4. Finally, now that the pointer is contained, we give a value.

Allocating Multiple blocks of Memory-calloc()

The calloc() function is the same as malloc() except it is used to allocate multiple c  memory management blocks of the same size then all bytes sets to zero.

Syntax:

It allocates contiguous space for ‘n’ blocks, each of the size of block_size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated memory block is returned.

Example:

An int array of 10 elements can be allocated as follows.

We can achieve the same using the malloc() function as below –

However, an area reserved by the malloc() function for the states that are undefined, the area allocated by the calloc function contains a 0.

Difference between malloc() and calloc()

  1. the malloc() allocates bytes of memory but calloc() allocates blocks of memory.
  2. the malloc() takes a single argument(memory required in bytes) but calloc() takes 2 arguments (number of variables to allocate memory, size in bytes of a single variable)
  3. The memory allocated using the malloc() function contains garbage values, the memory allocated by the calloc() function contains the value 0.

Resize the size of a Memory-realloc()

The realloc() function allows us to reset the size of the allocated area.

Syntax:

Where ptr is holding the current base address of the memory block and new_size holds the size in bytes.

Releasing the used memory-free()

The free() function is used to deallocate the allocated memory using the malloc() or calloc() function. It is always important to release the memory that is not in use, so it can be used in the future.

Syntax:

Note:- ptr must be a valid pointer to the address otherwise it can result in a system crash.

Example Program:

Below is the program where we have allocated memory for ptr integer pointer with the byte required for int data type, then assigned value 10. Finally released memory using free() function.

C Command Line Arguments

In C Programming Language we have built-in support for “Command Line arguments”. Command-line arguments allow us to pass the parameters to the C Program’s main() function when they are executed. We can pass the parameters from the command line itself.

Below is the prototype for main() when it is supposed to accept command-line arguments –

syntax:

There are two parameters passed to the main() function.

  • int argc
  • char *argv[]

The first parameter, argc is an integer that is used to define the number of parameters passed to main(), and the second parameter is argv, is an array of pointers to character strings which is consist of the list of these parameters. Each argument on the command line is separated by
spaces.

The program name will be stored in the first item in argv, followed by the list of the parameters. If the program name is followed by n parameters there will be n + 1 element in argv, ranging from argv[0] to argv[n]. argc will be automatically set equal to n + 1.

Example :

Assuming that the executable is called hello.

C Character Set

A character set in C Programming Language is set all valid characters that can be used to form words, numbers, and expression’s in source programs. The source character set is consist of the characters used for the source program text, while the execution character set is the set of characters used during the execution of the program.

It is not necessary that the source character set match and execution character set are the same.

Below is the list of characters available in C Programming Language –

The 26 lowercase Roman characters:

The 26 uppercase Roman characters:

The 10 decimal digits:

The 30 graphic characters:

Five white space characters:

Space( ),Horizontal tab (\t) , Carriage return(\v), Newline(\n) , form feed (\f)

C Escape Sequence

In C Programming Language c escape sequence is a special string comprising a backslash (\) followed by a letter or by a combination of digits used to control output on the monitor. C escape sequences are typically used to represent actions such as newline, carriage returns, tab movements, and nonprinting characters over the monitor. The following table lists the common ANSI c escape sequences and their meaning.

Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quotation mark
\ " Double quotation mark
\\ Backslash
\? Literal question mark
\ ooo ASCII character in octal notation
\x hh ASCII character in hexadecimal notation
\x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal.

C Unions

Union is the user-defined data type used to wrap up one or more variables that may be in different data types into a single variable at a single memory location. C unions are similar to the structure in concepts, except for allocating memory for its members.

Structure allocates storage space for all its members separately, whereas c unions allocate one common storage space for all its members.

Difference between structure and C unions

  • Union allocates one common storage space for all its members
  • In a union, if any of the data element’s values is changed then the other data element value even changes, i.e. the value of one data element of a union depends on all other data elements.
  • The only major advantage that a union has over structure is to save memory space.
  • Union holds value for one data type which requires larger storage among its members.

Syntax:

Example:

Accessing Union Members

Syntax:

To access members of a union you use the (.) operator, for instance: student1.name

 

 

C Structures

In C Programing Language we can use arrays when we want to hold multiple elements of the homogeneous data type in a single variable, but what if we want to hold heterogeneous data type elements, using the c structures you can wrap one or more variables that may be in different data types into one.

Syntax:

To define a structure, you use the struct keyword followed by the structure name. The variables which are declared inside the structure are called ‘members of structure’.

Example:

The student structure contains id as a positive integer, name as a string, percentage code as afloat.

Declaring structure

The above example only defines a student structure without creating any structure variable. To declare a structure variable, you can do it in two ways:

Declaring structure with variables together:

Declaring the C structures variable after you define the structure:

Note:– When declaring structure following points need to be kept in mind –

  • The structure is always terminated with semicolons (;).
  • Structure name as struct_name can be later used to declare c structures variables of its type in a program.

Accessing Structure Members

Member operator ‘.’ is used to accessing the individual structure members. It is also known as ‘dot operator’ or ‘period operator’.

Syntax:

Example Program:

C Strings

In C Programming Language a string variable represents sequences of characters that are always enclosed in double-quotes, like “Hello World” ended with a null character (‘\0’). This null character represents the end of the c strings. A string variable can be any length.

In C Programming Language we do not have a string data type like other programming languages, in c we can define a string as an array of characters or a pointer to characters.

<h2>Declaring strings</h2>
<h2>Declaring string as array of characters</h2>
<pre class=”lang:default decode:true”>char s[]=”string”;
OR,
char s[7]=”string”;
OR,
char s[]={‘s’,’t’,’r’,’i’,’n’,’g’,’\0′};
OR;
char s[7]={‘s’,’t’,’r’,’i’,’n’,’g’,’\0′};</pre>
<h2>Declaring string as a pointer to characters sequence</h2>
<pre class=”lang:default decode:true”>char* s = “string”;</pre>
<h2>Example – C program to read string from terminal</h2>
<pre class=”lang:default decode:true”>#include &lt;stdio.h&gt;
int main(){
char name[20];
printf(“Enter your name: “);
scanf(“%s”,name);
printf(“Your name is %s.”,name);
return 0;
}</pre>
<strong>Output:</strong>
<pre class=”lang:default decode:true”>Enter your name: steve
Your name is steve.</pre>
<h2>C String functions</h2>
In C Programming Language we have a rich set of function for string operations like –
<ul>
<li>Counting the length of a string.</li>
<li>Comparing two strings.</li>
<li>Copying one string to another.</li>
<li>Converting lower case string to upper case.</li>
<li>Converting upper case string to lower case.</li>
<li>Joining two strings.</li>
<li>Reversing string.</li>
</ul>
We must have included string.h header file before using these functions.
<table class=”table”>
<tbody>
<tr>
<td><strong> Function</strong></td>
<td><strong> Description</strong></td>
</tr>
<tr>
<td>strcat (str1, str2)</td>
<td> Concatenates str2 at the end of str1.</td>
</tr>
<tr>
<td>strcpy (str1, str 2)</td>
<td> Copies str2 into str1</td>
</tr>
<tr>
<td>strlen (strl)</td>
<td> It returns the length of str1.</td>
</tr>
<tr>
<td>strcmp (str1, str2)</td>
<td> Returns 0 if str1 is same as str2. Returns &lt;0 if strl &lt; str2. Returns &gt;0 if str1 &gt; str2.</td>
</tr>
<tr>
<td>strchr (str1, char)</td>
<td> Returns pointer to first occurrence of char in str1.</td>
</tr>
<tr>
<td>strstr (str1, str2)</td>
<td> Returns pointer to first occurrence of str2 in str1.</td>
</tr>
<tr>
<td>strcmpi (str1, str2)</td>
<td> Same as strcmp() function. But, this function negotiates case. “A” and “a” are treated as same.</td>
</tr>
<tr>
<td>strdup()</td>
<td> duplicates the string</td>
</tr>
<tr>
<td>strlwr()</td>
<td> converts string to lowercase</td>
</tr>
<tr>
<td>strncat()</td>
<td> appends a portion of string to another</td>
</tr>
<tr>
<td>strncpy()</td>
<td> copies given number of characters of one string to another</td>
</tr>
<tr>
<td>strrchr()</td>
<td> last occurrence of given character in a string is found</td>
</tr>
<tr>
<td>strrev()</td>
<td> reverses the given string</td>
</tr>
<tr>
<td>strset()</td>
<td> sets all character in a string to given character</td>
</tr>
<tr>
<td>strupr()</td>
<td> converts string to uppercase</td>
</tr>
<tr>
<td>strtok()</td>
<td> tokenizing given string using delimiter</td>
</tr>
</tbody>
</table>

C Pointers

Pointers is one of the most powerful features available in C Programming Language. A pointer is a special type of variable that refers to the address of other data objects or variables.

Variable can be of any data type i.e int, float, char, double, short, etc. C Pointer is used for dynamic memory allocation.

Syntax to Declare C Pointer Variable:

data_type specifies the type of pointer, then an asterisk (*) followed by the pointer name.

Example:

Example Program to Demonstrate Pointer

Output: