Welcome

C Programming Tutorial


C Functions

In C all executable code contained with in the function. Breaking the whole task into subtaks. or Decompose the whole task into smaller tasks, each function is associted with task. C follows Top-Down Approrach. Functions are defined as individual objects that cannot be nested. C Programs begins with function called main,which can call other functions and libray functions such as printf and sqrt etc., Function Operate with Program variables.

Benefits Of Functions

  • Functions allow a program to be split set of subproblems,which in turn may be further split into smaller subproblems. This divide-and-Conquer approach means that small parts of the program can be written,tested and debugged in isolation without interfering with other parts of the program.
  • Functions can wrap difficult algorithms into simple and intuitve interface
  • Functions avoid code duplication. If a perticular segment of code is required in several places, a function provides tidy means for writing the code only once. This is of considerable benefit,if the code segment is later altered.

All functionality in C program lies in functions only,There is 2 things programmers should understand declaring a functions and defining functions

declaring a function is nothing but prototype, function name, arguments and return type. Defining a function means function name , arugument names,and return type in addition to that actual logic with in the function

usually all function prototypes will go to header files, function definitions will goto source files

int sum(int,int) is a prototype

int sum(int x,int y){return x+y;} is a function definition.

Forward declaring a function, some compiler may force forward declaring a function, i.e function prototype should appear before a main function

Rewrite the function lower , which converts upper case letters to lower case, with a conditional expression instead of if-else .

defining a function syntax:

return type of function is optional, if no type is specified returns int, function_name adheres to naming rules of 'C' language identifiers and it has optional arguments list, if no arguments are specified, empty () brackets must be specified.

	[return type]  function_name([arguments])
	{
		//function body
	}

Valid function defintions

	void display(){}
	
	void display(void){}
	
	#empty argument functions can be declared/defined in above 2 ways. passing empty () or passing void type

	int  add(int x,int y){return x+y;}
	

Passing arguments to functions

arguments can be passed to functions as follows

Here we have test method,which takes 3 int parameters, x,y,z

//x,y,z are also knows formal arguments
void test(int x ,int y, int z)
{
        printf("x=%d,y=%d,z=%d\n",x,y,z);
}

calling test function in main function, main method calls test method with 3 arguments,x,y,z, which are initialized to 1,2,3 repectively. these 3 arguments values will be copied to test method arguments.All primitive data types values will be copied to formal paramters in function. calling function which calls test method (here main method) parameters also called as actual parameters.


int main()
{
        int x=1,y=2,z=3;
        test(x,y,z);//x,y,z also known as actual arguments
        return 0;
}

Functions and Return Type

Functions can return a value using return statement, return statement has 2 jobs

  • returning value to the calling function
  • returning control to the calling function

return statements takes optional argument.

return statement syntax

		return [expression];
	

if return type is void, then return statements takes no arguments. i.e function simply calls "return;"
if return type is other than void, in that case return expression, will be called.

Example:

int abs(int x){ if(x<0) x=-x;return x;}

calling abs method x=abs(-1); x has value 1;

int marks(int m1,int m2,int m3){if(m1 <0 || m2 <0||m3<0){printf("marks should not be negative");return;}//else do calculations here}

In this case return statement is with empty argument list,it passes control to the calling function

Functions and Variables

Within functions Variables can be created, by default all variables are automatic.Means its life time is end of the function or with-in the block of code.

variables can be

  • automatic
  • static
  • register
  • extern

Functions and Stack

Any function which has arguments, internally uses stack data structure. arguments are evaluated from left-to-right and will be pushed to stack.Once the function body completes execution of the statements, arguments will be poped one by one.

Recursion

            function calls itself.Whenever there is repetetive code, recursion does best job. Invoking a function, all arguments will be pushed to stack, while returning all arguments will be poped from stack. misusing recursion will lead to stack overflow.

Display numbers without using loops or using Recursion

    In this example recursion will be right choice, instead of using goto statements,user can use recursion

#include <stdio.h>
void print(int);
int main()
{
	printf("printing numbers with recursion\n");
        int N=1;
        print(N);
        return 0;
}

void print(int N)
{
        if(N==11) return;
        printf("%d ",N);
        print(N+1);
}
          
	
output:
printing numbers with recursion
1 2 3 4 5 6 7 8 9 10


Mathematical Functions

      C standard library contains variety of functions to perform methematical operations.Prototypes are included in header file Math.h. The math functions all returns a type double.

  • sqrt()
  • ceil()
  • abc()
  • labs()
  • floor()
  • modf()
  • pow()
  • fmod()

sqrt - square root function

Finds square root of the number, number should be 0 or greater. returns double value. int ,short,float implicitely converted into double

sqrt syntax:
		double sqrt(double)
	
sqrt syntax:
		sqrt(5);  //2.236068
		sqrt(0); //0
		sqrt(625);//25.000000
		sqrt(-1); // -nan  for negative values it doesn't throw error but displays nan  - not a number
	

ceil

Returns smallest integer not less than its parameter,

ceil syntax:
		double ceil(double)
	
ceil example:
		ceil(5.49);  //6.000000
		ceil(-0.11); //-0.00000
		ceil(9.98);//10.000000
		ceil(-1.01); //-1.000000
	

floor -

returns largest integer not greater than its number

floor syntax:
		double floor(double)
	
floor example:
		floor(11.49);  //11.000000
		floor(0.00001); //0.000000
		floor(-11.89); //-12.00000
	

abs - absolute value

Returns absolute value

abs syntax:
		int abs(int)  //for int
		long labs(long) //for long
	
abs syntax:
		
	

modf

splits x into integral and fractional part. the fractional part is returned by the function,fractional part is assigned to y

modf syntax:
		double modf(double x,double*y)
	
modf example:
		double x=100.001,y;
		printf("%f",modf(x,&y)); //100.000000
		printf("%f",y); //y=0.001000
	

pow -

b is a base and p is the power, returns value power to the base b.

pow syntax:
		double pow(double b,double p)
	
pow syntax:
		pow(2,3);  //8.000000
		pow(10,3); //1000.000000
		pow(10,-3);//0.0010000
		pow(-1,0.1); // -nan  for negative values it doesn't throw error but displays nan  - not a number
		pow(0,-0.1); // inf  for negative values it doesn't throw error but displays nan  - not a number
	

fmod -

Returns floating-point remainder of x/y.

fmod syntax:
		double fmod(double,double)
	
fmod syntax:
		fmod(3.3333,3); //0.333300
	




String Functions

      Text data in C stored as a strings. C has built-in String functions, very useful in small or large applications, these already tested functions, finding length of the string, contatenating the strings, comparing two strings, finding a characters in a string, convert string to number etc.,

  • strlen()
  • strcpy() , strncpy() strdup()
  • strcat() strncat()
  • strcmp() strncmp() strcmpl()
  • strchr() strrchar() strcspn() strspn() strpbrk() strstr()
  • strrev() strset() strnset()
  • strlwr() strupr()
  • atoi() atof() atol()

strlen->string length function

      finds strings length, returns int ,it excludes null character

    char *p="hello";
    int i = strlen(p); //returns 5 , excludes null character
    char carr[]={"hello world!"};
    i = strlen(carr); //12
    char c1[3]={'a','b'};
    i= strlen(c1); // returns 2.
    char c2[3]={'a','b','c'};
    i= strlen(c2); // returns 15. There is no space for NULL character, so it returns unexpected value 
    char c3[10]={"ab"};
    i= strlen(c3); // returns 2.  remaining elements filled with NULL character.strlen excludes null characters.

strcat() strncat() -> String concatenation

      strcat string function concatenates 2 strings,destination buffer should have enough space to accomodate source buffer

strcat,strncat syntax:
	char * strcat(char* dest, char * const src);

	concatenate firstname and lastname with space in between.
    char full_name[30]={""},first[]={"sam"},last[]={"uncle"};

    strcat(full_name,first));
    strcat(full_name," "))
    strcat(full_name,last))  //"sam uncle"
	//rewrite above with nested strcat functions
    strcat(strcat(strcat(full_name,first)," "),last); //"sam uncle"

strcmp() strncmp() strcmpl()- String comparisions

      compares 2 strings , returns integer value. strings are equal returns 0, string1 greater than string 2 ASCII difference posive value displayed otherwise negative value displayed

strcmp strncmp strcmpl syntax:
	int strcmp(const char*s1,const char*s2)
	int strncmp(const char*s1,const char*s2, size_t n)
	int strcasecmp(const char*s1,const char*s2);
strcmp strncmp strcmpl example:
	strcmp is case-sensitive

	char s1[]={"sam"},s2[]={"sam"};
	strcmp(s1,s2); // returns 0

	//string1 is greater than string2 
	char s1[]={"sam"},s2[]={"Sam"}; //ASCII value of 's'  115  'S' 83 
	strcmp(s1,s2); // returns 32  115-83 = 32

	//string2 is greater than string1
	char s1[]={"Sam"},s2[]={"sam"}; 
	strcmp(s1,s2); // returns -32 (83-115=-32)

	strcasecmp(s1,s2);  // returns 0. because it ignores case.

strcpy() , strncpy() strdup()- String copy

      copies source string into destination. Destination buffer should have enough space to accomodate source buffer

strcpy() , strncpy() strdup() syntax:
	int strcpy(char*dest,const char*src)
	int strncpy(char*dest,const char*src, size_t n)

strcpy() , strncpy() strdup() example:
copies firstname and lastname with space in between.
    char full_name[30]={""},first[]={"sam"},last[]={"uncle"};

    strcat(full_name,first));
    strcat(full_name," "))
    strcat(full_name,last))  //"sam uncle"
	//rewrite above with nested strcat functions
    strcat(strcat(strcat(full_name,first)," "),last); //"sam uncle"

strlwr() , strupr() - converts lower case to upper case, upper case letters to lower case

      strlwr function converts all upper case letters converted into lower case, strupr function converts all lower case letters to upper case

strlwr() , strupr() syntax:
	char* strlwr(char*src)
	char* strupr(char*src)

strlwr() , strupr() example:
	strlwr("Hello"); //output: "hello" converts Capital 'H' to lower case 'h'
	strupr("Hello"); //output: "HELLO" converts all lower case letters to upper case letters.

strrev() strset() strnset() - reverses given string

      strrev reverses a order of given string ,

strrev() strset() strnset() syntax:
	char * strrev(char*src);
strrev() strset() strnset() example:
	strrev("Hello"); //output: "hello" converts Capital 'H' to lower case 'h'
	strupr("Hello"); //output: "HELLO" converts all lower case letters to upper case letters.

strchr() strrchar() strcspn() strspn() strpbrk() strstr() - searching functions

      strchr function searches a character, if found returns from that character to rest of the string otherwise NULL ,
strrchr function searches a last occurence of the character, if found returns from that character(last occurence) to rest of the string otherwise NULL

strchr() strrchar() strcspn() strspn() strpbrk() strstr() syntax:
	char * strchr(char*src);
	char * strrchr(char*src);
strchr() strrchar() strcspn() strspn() strpbrk() strstr() example:
	strchr("hello",'e'); //"ello"
	strrchr("hello",'l'); //"lo"


Functions with Variable-Size Argument List

      Like scanf,printf which are variable argument list functions, user can pass N number of argumnets to satify his condition. Similaryly Programmer can write his function, which can accept variable number of arguments.
for ex:

    func(3,1,2,3);
    func(5,"sam","jhon","jenny","mariam","symonds");

above 2 functions , first argument is fixed number of argumenets, telling the function that those many arguments are passed to the function. and also using same function with different functionality can be achevived. first version has 3 numbers, second version has 5 strings or character arrays...

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

void func (int fixed,...);
int main(void)
{
        //func(3,12,3,3);       
        func(3,"ram","sam","jhon");

        return 0;
}

void func (int fixed,...)
{
        va_list list;

        va_start(list,fixed); //start

        for(int i=0; i < fixed; i++)
        {
                printf("%s ",va_arg(list,char* ));  //process
        }

        va_end(list); //cleanup
}     

>> C Storage Classes

ADS