Showing posts with label C Programming. Show all posts
Showing posts with label C Programming. Show all posts

Wednesday, March 23, 2016

Structures in C

Using structures, you can define your own data type which can store multiple dissimilar primitive data types. Actually this type of data types is called user defined data types. For example, you can represent any real life object properties like student –
  • roll number – integer
  • name – character array
  • class – integer
  • section – character
  • last year marks in percentile – float
  • school name – character array
Here you can see that there are different data types which represent a particular student. So, using structure you can do this very easily in C.
Structure Declarations
In C, to define a structure there is a keyword “struct” is used. The syntax of the statement is like below.
struct 
{
 member_name;
 member_name;
 member_name;
...
} <one or more structure variables>;
For example, the above mentioned student declaration would be like this
struct student
{
int roll_number;
char name[50];
int class;
char section;
float marks;
char school_name[50];
} student_1;
Here, student_1 is the structure variable. You can also declare structure variable like below:
struct student student_2;
There is another good way to declare structure and its variables, using typedef keyword. The typedef keyword, actually defines a new data type by which you can use a data type the same way like other primitive data types.
typedef struct student
{
int roll_number;
char name[50];
int class;
char section;
float marks;
char school_name[50];
} student;
Here, using typedef we are defining a new data type called student. Now we can use this data type just like any other data types we know like int float etc. for variable declarations.
student student_1,student_2;
You can also initialize the structure variables also to zero like this:
student student_1 = {0};

Sunday, March 6, 2016

Recursive Functions

Recursive functions are those functions which call themselves directly or indirectly. If a function calls itself again, that will make a repetition and will work like a loop. In order to make a logical end to the repetitive call, we have to add an expression to break the flow of recursive call. Consider the program of factorial which finds the factorial of the input number. It can be written using recursive function as given below.

Recursive Function Example in C

  1. #include<stdio.h>
  2. int factorial(int n);
  3.  
  4. void main()
  5. {
  6. int num;
  7. int fact;
  8. printf("Enter the number:");
  9. scanf("%d", &num);
  10.  
  11. fact = factorial(num);
  12. printf("Factorial of %d is %d", num, fact);
  13. }
  14.  
  15. int factorial(int n)
  16. {
  17. if(n == 1)
  18. {
  19. return 1;
  20. }
  21. else
  22. {
  23. return (n * factorial(n -1));
  24. }
  25. }
Let’s take the input number as 3. Then the factorial function is called with value 3. Inside the function it will check whether 3 is equal to 1 and then execute the 'else' statements. The return statement will look like 'return (3 * factorial (2))'. Now 'factorial(2)' will again enter the 'else' statement as the 'if' condition fails. This time it will return '(2 * factorial(1))'. Now 'factorial(1)' returns value 1 which will result the output (3 * (2 * 1)) i.e. 6.
One thing to remember while using recursive function is that if you omit the check expression or if the expression never be satisfied, it will cause an infinite loop. Recursion is another way to simulate loop and can be replaced by a simple loop statement (also called iteration)

Thursday, March 3, 2016

Function with Return Value

Function as mentioned earlier can return some value. The number of values that can be returned by a function is restricted to 1 in C. If a function calculates more number of output values, you can use a structure/union to hold each of them and return it. The type of value returned by the function must be defined in the function prototype and definition. To illustrate function with return value a simple program is presented below.

  1. #include<stdio.h>
  2. int add(int a, int b);
  3.  
  4. void main()
  5. {
  6. int sum = 0;
  7. sum = add(23, 35);
  8. printf("Sum : %d", sum);
  9. }
  10.  
  11. int add(int a, int b)
  12. {
  13. int c = a + b;
  14. return c;
  15. }
In the above example, the function 'add()' takes two arguments of integer type and returns an integer value. Notice the return statement in the 'add()' function which returns the value to the caller.

Wednesday, March 2, 2016

Concepts Associated with Functions in C

A function is not executed until it is called (invoked) from the program. By function call we mean, the program provides the function with input data in the form of arguments. The value of the argument is passed to the function and copied in the formal arguments. If the formal arguments are modified inside the function it will not affect the value of the actual arguments in the program unless the arguments are passed as pointers.
  1. #include<stdio.h>
  2. void function1(int a);
  3.  
  4. void main()
  5. {
  6. int i = 3;
  7. function1(i);
  8. printf("Value of i : %d", i);
  9. }
  10.  
  11. void function1(int a)
  12. {
  13. a++;
  14. printf("Value of a:%d\n", a);
  15. }
In the above example, value of variable 'a' will be printed as 4 but the value of 'i' will be printed as 3. Because, even if value of the argument is incremented inside the function, it would not affect the value of variable 'i' in 'main'. When the function is called, the program execution goes to the function and after executing the statements in the function, it returns to the same position.

Function parameters

The function parameter can be of any data type, charintfloatstring or even an array/user defined data type. The arguments passed from the caller (from where the function is called), must be of the same data type as of function parameters. If there is a mismatch between those two, it will generate a compiler error. Even sometimes the compiler may fail to spot the difference, in which case your program may act erroneously.

Variable Argument Functions in C

C function can also have variable number of arguments. For example functions like 'printf'and 'scanf' can take any number of arguments. The variable argument function has a function prototype like the one given below
data_type function_name(int, data_type argument1, …);
The three dots (…) in function prototype defines that it is variable argument. Note that the first argument is an integer which represents the number of arguments. Some utility methods are required to make use of variable arguments in C and it is defined inside header file 'stdarg.h'.

How to Use Variable Argument Function in C

First step in making use of variable arguments in the function definition is to use the macro,'va_start', which is defined in header file 'stdarg.h'. This macro initializes a variable of type'va_list' with the argument list. Then we need to use 'va_arg' macro and 'va_list'variable to access each individual parameters. When the processing is finished, use the macro'va_end' to release the memory used by 'va_list'.

Variable Argument Functions Example

  1. #include <stdio.h>
  2. #include <stdarg.h>
  3.  
  4. int calculateSum(int count,...)
  5. {
  6. va_list valist;
  7. int sum = 0.0;
  8. int i;
  9. va_start(valist, count);
  10. for (i = 0; i < count; i++)
  11. {
  12. sum += va_arg(valist, int);
  13. }
  14. va_end(valist);
  15. return sum;
  16. }
  17.  
  18. int main()
  19. {
  20. printf("Sum of 1, 2, 3 = %d\n", calculateSum(3, 1, 2, 3));
  21. printf("Sum of 1, 2, 3, 4 = %d\n", calculateSum(4, 1, 2, 3, 4));
  22. }

Tuesday, March 1, 2016

Functions with Multiple Parameters

functions can have more than one argument. In that case the function definition, prototype and the function call must have arguments separated by commas. Consider the simple program where the function 'print_bigger' accepts two arguments.
  1. #include<stdio.h>
  2. void print_bigger(int first, int second);
  3.  
  4. void main()
  5. {
  6. print_bigger(15, 27);
  7. }
  8.  
  9. void print_bigger(int first, int second)
  10. {
  11. if(first > second)
  12. {
  13. printf("%d is bigger", first);
  14. }
  15. else if(first == second)
  16. {
  17. printf("both number are same");
  18. }
  19. else
  20. {
  21. printf("%d is bigger", second);
  22. }
  23. }
Here the function 'print_bigger' takes two arguments and prints the number which is bigger than the other or prints "both number are same" if both arguments have the same value.

User Defined Functions and Library Functions

We have already seen both user defined and library functions. User defined functions are the functions that are defined by the programmer and not provided by C. The library functions or system defined functions are provided by C libraries, like 'printf''scanf' etc.
There are a lot of library functions available in C. The standard C library provides functions like'printf', 'scanf', 'putc', 'getc', 'puts', 'gets' etc. Functions like 'toupper', 'tolower', 'isalpha' etc., have their definitions in header file 'ctype.h''sin', 'cos', 'sqrt' have definition in 'math.h' file.

Monday, February 29, 2016

Use of Functions in C

In C, a function is nothing but a self-contained block of code that can be accessed by specifying its name and providing the appropriate arguments to it from any part of the program. The argument list must be separated by commas. If the function does not require any arguments, then the function name will be followed by the empty parenthesis. The arguments used in the function call are known as actual arguments. The arguments in the first line of function definition are called formal arguments or actual parameters. The actual arguments must be of the same data type as the formal arguments. During the function call, values of actual arguments are copied into the formal arguments
Sometimes functions return values too. In that case, the value returned by the function can be assigned to a variable using assignment operator. Function calls may happen multiple times from different parts of the program and the actual argument may vary. But in all function calls the different arguments must be of the same data type as the formal argument and also the number and order of arguments must be same.
The general form of function prototypes looks like ...
  1. data_type function_name(data_type1 argument1, …, data_typeN argumentN);
and the function call will look like -
  1. function_name(argument1, argument2, , argumentN) ;

Example of a Function in C

A simple program with function call will look like this...
  1. #include<stdio.h>
  2. void print_hello();
  3.  
  4. void main()
  5. {
  6. print_hello();
  7. }
  8.  
  9. void print_hello()
  10. {
  11. printf("Hello world\n");
  12. }
This program just prints "Hello world" on the screen. The line after '#include' directive is called a function prototype. It declares that function 'print_hello' does not return anything and does not take any arguments. The function call is inside the 'main()'. After 'main', there is function definition which defines what the function does.

Placement of the Function

The function prototype should be defined before 'main' function, so that when the functions are called, compiler can decide whether the function exists or not or is on a different file. The function call can be placed in the 'main' function or even in another function body. The function body or definition can be placed before 'main' or after 'main' . If the function definition is placed before the invocation, then there is no need for function prototype.
In case the whole program is divided in multiple files, the function prototypes most likely to be included in the header file (files with '.h' extension). The file from which the function is invoked must include the header file containing the prototype. The function body in that case can be in a source file ('.c') or can be placed inside the header file as well.

Sunday, February 28, 2016

Conditional Compilation pre-processors

There are other C pre-processors like #if, #elif, #else, #endif etc which are used for conditional compilation. If we want to skip over a part of code during compilation, we can use these pre-processors. This is mostly useful when we write code which depends on the operating system. Suppose, some code we have written is not applicable for Windows and only applicable for Linux machines, we can skip the code, when compiling from Windows machine using this pre-processors. The general form of #ifdefis

  1. #ifdef macroname
  2. Statement block;
  3. #endif
The '#ifdef' stands for 'if defined'. It means that if the macro name is already defined somewhere, then the statement block will be included in the source for compilation, otherwise it will be skipped. The #ifdefis accompanied by an #endif statement, which marks the end of statement block. We can use #ifndef, which is applicable when we want to compile part of program if the corresponding macro name is not defined. Like nested if...else , #ifdef also can be combined with #elif and #else. We can use them as given in the below example.

Conditional Compilation Example in C

  1. #ifdef SYSTEM==LINUX
  2. statement block 1;
  3. #elif SYSTEM==WINDOWS
  4. statement block 2;
  5. #else
  6. statement block 3;
  7. #endif

Predefined Macros

Apart from the above mentioned macros, ANCI has a set of predefined macros which can be used for functionalities that's used commonly in application programs. They are explained below.
MacroDescription
__DATE__Gives current date in MMM DD YYYY format
__TIME__Gives current time in HH:MM:SS format
__FILE__Gives the current file name
__LINE__Gives the current line number of source code
__STDC__Gives 1 when the compilation follows ANSI standard

Thursday, February 25, 2016

#pragma Pre-processor Directive

Pragma is used to turn on or off some of compiler/system features. Pragma's operation is system and compiler dependent. So, all pragmas may not work with all the compilers. When pragmas are encountered, the default behaviour of the compiler is overwritten by the options provided by pragmas. One of such pragma is 'pragma startup' and 'pragma exit'. The pragma startup is used to specify function that will be called before main function and pragma exitis used to specify function that would be called just before the program exits. Consider the example program

Pragma Example in C

  1. #include<stdio.h>
  2.  
  3. void function1();
  4. void function2() ;
  5.  
  6. #pragma startup function1
  7. #pragma exit function2
  8.  
  9. void main()
  10. {
  11. printf("In main function");
  12. }
  13.  
  14. void function1()
  15. {
  16. printf("In function1\n");
  17. }
  18.  
  19. void function2()
  20. {
  21. printf("In function2");
  22. }
  23.  
  24. Output:
  25. In function1
  26. In main function
  27. In function2 .