0% found this document useful (0 votes)
25 views10 pages

EM2101 Coding Techniques 1u5

Uploaded by

Santhosh kumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views10 pages

EM2101 Coding Techniques 1u5

Uploaded by

Santhosh kumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

EM2101 CODING TECHNIQUES 1

UNIT 5: APPLICATION DEVELOPMENT AND ADVANCED CONCEPTS


Bit Fields
 A word can be divided into a number of bit fields.
 A bit field is one bit or set of adjacent bits within a word.
 C allows use of bit fields to hold data items. Thus several data items can be packed in
a word of memory.
 The size of a bit field varies from 1 to16 bits in length.
 Direct manipulation of bit fields are allowed when the bit fields are defined using the
format given below.
 The format of a bit field definition is similar to structure definition.
struct tag_name
{
data_type mem_name1: field_width1;
data_type mem_name2: field_width2;
..
..
data_type mem_name : field_widthn;
}var1, var2,…..varn;
 The data type of the members can be int or signed int or unsigned int only.
 The field_width specifies the number of bits used by that member large enough to
store the range of value of that member (n bits are capable of storing the value ranging
from 0 to 2n-1.
 A bit field is always interpreted as integral data type.

The following are the limitations of bit fields:


 Bit fields do not have addresses.
 Bit fields cannot be read using scanf( ) function.
 Bit fields cannot be accessed by pointers.
 Bit fields are not arrays.
 Bit fields cannot store the values beyond the limits. If larger values are assigned the
output is undefined.
Typedef
 typedef is a keyword used in C language to assign alternative names to existing
datatypes.
 Its mostly used with user defined datatypes, when names of the datatypes become
slightly complicated to use in programs.
 Following is the general syntax for using typedef,
typedef <existing_name> <alias_name>
 The typedef feature allows us to give an alternative (possibly short and more
meaningful) name to an existing data type and improve program readability.
 For example, instead of using the int data type to declare variables to represent marks
in three subjects, we can associate a more meaningful name (say Marks)for the int
data type using typedef as:
typedef int Marks;
 Now we can declare variables using the new type name Marks as shown below:
Marks phy, chem, math;
 It should be understood that Marks is just another name for the int data type and it
does not restrict the values of variables phy,chem and math to the desired range, say 0
to 100.
 Also, we can perform all the operations on these variables that we can perform on
variables of type int including the use of the %d format in the scanf and printf
statements
Using typedef with Structures
#include<stdio.h>
#include<string.h>
typedef struct employee
{
char name[50];
int salary;
}emp;

void main( )
{
emp e1;
printf("\nEnter Employee record:\n");
printf("\nEmployee name:\t");
scanf("%s", e1.name);
printf("\nEnter Employee salary: \t");
scanf("%d", &e1.salary);
printf("\nstudent name is %s", e1.name);
printf("\nroll is %d", e1.salary);
}

Command line arguments

 Definition: Command line arguments are nothing but simply arguments that are
specified after the name of the program in the system’s command line, and these
argument values are passed on to your program during program execution.
 Command line argument is a parameter supplied to the program when it is invoked.
Command line argument is an important concept in C programming. It is mostly used
when you need to control your program from outside.
 Command line arguments are passed to the main() method.
 In order to implement command line arguments, generally, 2 parameters are passed
into the main function:
1. Number of command line arguments
2. The list of command line arguments
 The basic syntax is:
int main( int argc, char *argv[] )
{
.
.
// BODY OF THE MAIN FUNCTION
.
.
}
Another way to implement command line arguments is:
int main( int argc, char **argv[] )
{
.
.
// BODY OF THE MAIN FUNCTION
.
.
}
 argc: It refers to “argument count”. It is the first parameter that we use to store the
number of command line arguments. It is important to note that the value of argc
should be greater than or equal to 0.
 agrv: It refers to “argument vector”. It is basically an array of character pointer which
we use to list all the command line arguments.
Example for Command Line Argument
#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
Remember that argv[0] holds the name of the program and argv[1] points to
the first command line argument and argv[n] gives the last argument. If no
argument is supplied, argc will be 1.

Recursive Functions
 In C programming, a function is allowed to call itself.
 A function which calls itself directly or indirectly again and again until some
specified condition is satisfied is known as Recursive Function.

 A recursive function is a function defined in terms of itself via self-calling


expressions.
 This means that the function will continue to call itself and repeat its behavior until
some condition is satisfied to return a value.
Syntax of recursive function in C:-
void do_recursion()
{
... .. ...
do_recursion();
... .. ...
}
int main()
{
... .. ...
do_recursion();
... .. ...
}
Flow chart of Recursion:

In order to prevent infinite recursive call, we need to define proper


exit condition in a recursive function.
Example #1: C Program to show infinite recursive function
#include<stdio.h>
int main()
{
printf("Hello world");
main();
return 0;
}
 In this program, we are calling main() from main() which is
recursion. But we haven’t defined any condition for the program to
exit.
 Hence this code will print “Hello world” infinitely in the output
screen.
Example: Factorial of a number using recursion function.
#include<stdio.h>
#include<conio.h>
int fact(int n); /* Function Definition */
void main(){
int num, res;
clrscr();
printf("Enter positive integer: ");
scanf("%d",&num);
res = fact(num); /* Normal Function Call */
printf("%d! = %d" ,num ,res);
getch();
}
int fact(int n) /* Function Definition */
{
int f=1;
if(n <= 0)
{
return(1);
}
else
{
f = n * fact(n-1); /* Recursive Function Call as fact() calls itself */
return(f);
}
}
Output
Enter positive integer: 5↲
5! = 120
User Defined Libraries
 Library functions are inbuilt functions which are available in common place called C
library. Whereas, User defined functions are the functions which are written by us for
our own requirement.
 It is possible to add, delete, modify, and access our own user-defined function to or
from the C library.
 The advantage of adding a user-defined function in C library is that these function
will be available for all C programs once added to the C library.
 We can use this function in any C program as we use other C library functions.
 In the latest version of GCC compilers, compilation time can be saved since these
functions are available in the library in the compiled form.
 Normal header files are saved as “file_name.h” in which all library functions are
available. These header files contain source code and this source code is added in
main C program file where we add this header file using “#include <file_name.h>”
command.
Steps for adding our own functions in C Library:
STEP 1: For example, below is a sample function that is going to be added to the C
library. Write the below function in a file and save it as “addition.c”
addition(int i, int j)
{
int total;
total = i + j;
return total;
}
STEP 2: Compile “addition.c” file by using Alt + F9 keys (in turbo C).

STEP 3: “addition.obj” file would be created which is then compiled form of “addition.c”
file.
STEP 4: Use the below command to add this function to library (in turbo C).
c:\> tlib math.lib + c:\ addition.obj
+ means adding c:\addition.obj file in the math library.
We can delete this file using – (minus).
STEP 5: Create a file “addition.h” & declare prototype of addition() function like below.
int addition (int i, int j);
Now, addition.h file contains a prototype of the function “addition”.
STEP 6: Let us see how to use our newly added library function in a C program.

Preprocessor and Macros

The pre-processor is a unique feature in C that processes the source code program before it
passes through the compiler. It is mostly supplied along with the C compiler or sometimes as
a separate tool. The following facilities are provided by the pre-processor :
1. File inclusion
2. Substitution facilities
3. Conditional compilation
These facilities are controlled in a program by a pre-processor control lines or directives.
Generally, the pre-processor directives appear before the main function but they may appear
anywhere in a C program. A directive may influence that part of the program which follows.
It modifies the C sourcecode before compilation. Any pre-processor directive must begin
with the character #. Any number of whitespace characters may follow or precede #. There
are different types of directives which are indicated by the following keywords :
define, elif, else, endif, error, if, ifdef, include, line, undef
Sr.No. Directive & Description
1 #define- Substitutes a preprocessor macro.
2 #include- Inserts a particular header from another file.
3 #undef -Undefines a preprocessor macro.
4 #ifdef- Returns true if this macro is defined.
5 #ifndef- Returns true if this macro is not defined.
6 #if-Tests if a compile time condition is true.
7 #else -The alternative for #if.
8 #elif -#else and #if in one statement.
9 #endif -Ends preprocessor conditional.
10 #error -Prints error message on stderr.
11 #pragma -Issues special commands to the compiler, using a standardized method.

1. File Inclusion

2. Substitution Facilities
3. Defining Macros
Macro is a piece of code that is replaced by the value of the macro throughout the
program. You can define a macro with #define directive. At the end of defining a
macro, you don’t have to put a semicolon(;) to terminate it.
Types of Macros in C
There are 2 types of macros present in C such as:-
 Object-like Macros.
 Function-like Macros.
1. Object-like Macros in C
It is a simple type of macro. In this object-like macro, the macro will be replaced
by it’s value. Object-like macros mainly used to represent numeric constants.
Example:-
#define PI 3.14
Example:- Object-like Macros
#include <stdio.h>
#define SIDE 4
int main() {
int area;
area = SIDE*SIDE;
printf("Object Like Macros!\n");
printf("Area is: %d",area);
return 0;
}
Output:-
Object Like Macros!
Area is: 16
2. Function-like Macros in C
In C, function-like macros are much similar to a function call. In this type of
macro, you can define a function with arguments passed into it.
Example:-
#define AREA(a) (a*a)
Example:- Function-like Macros
#include <stdio.h>
#define AREA(s) (s * s) // macro with argument
int main()
{
int s1 = 10, area_of_square;
area_of_square = AREA(s1);
printf("Macros with arguments!\n");
printf("Area of square is: %d", area_of_square);
return 0;
}
Output:-
Macros with arguments!
Area of square is: 100
In the above example, the compiler finds the name of the macro (AREA(a)) and
replaces it with the statement (a*a).
4. Pre defined Macros
There are some predefined macros present in C. And it cannot be modified. Below
are some predefined macros.

MACRO What it does


__DATE__ Current date as MMM DD YYYY format.
__TIME__ Current time as HH:MM:SS format.
__FILE__ Contains current filename.
__LINE__ Contains current line number.
__STDC__ Defined as 1 when the compiler compiles.

Example:- Predefined Macros


#include <stdio.h>
int main() {
printf("TechVidvan Tutorial: Predefined Macros!\n\n");
char filename[] = __FILE__;
char date[] = __DATE__;
char time[] = __TIME__;
int line = __LINE__;
int ansi = __STDC__;
printf("File name is: %s\n", filename);
printf("Date is: %s\n", date);
printf("Now time is: %s\n", time);
printf("Current line number: %d\n", line);
printf("Compilation Success: %d\n", ansi);
}
The above code is saved in a file named HelloWorld.c.
Output:-
Predefined Macros!
File name is: main.c
Date is: Jun 24 2021
Now time is: 09:47:33
Current line number: 15
Compilation Success: 1
Why to use Macros in C?
 It becomes handy when you use it for anything magic number or string related.
 You can use macros to create automatic loop unrolling.
 With macros, you can do some things which you cannot do with functions like Token
Pasting.
 You can use a macro for writing debugging messages also.

You might also like