You are on page 1of 93

Concepts of programming (using C)

By: Er. Prabin Silwal

Why C?
Learning C programming language is basic to
learn all other programming languages such as
C++, Java, Python, etc.
Because, all other advanced programming
languages were derived from C language
concepts only.

C data types
C data types are defined as the data storage
format that a variable can store
Data types are used to define a variable before to
use in a program.
Size of variable, constant and array are
determined by data types.
There are four data types in C language. They are,
1.Basic data types: int, char, float, double,long
2.Enumeration data type: enum
3.Derived data type: array, structure, union, pointer
4.Void data type: void


Since we have to program
considering limited
memory we choose the data types wisely.
We may use data types from both C and C++, like:
Data Type

Range

Bytes

Short Signed Integer

-32768 to +32767

Short Unsigned Integer

0 to 65535

Signed Integer

-2147483648 to +2147483647

Unsigned Integer

0 to 4294967295

Float

-3.4e38 to +3.4e38

Double

-1.7e308 to +1.7e308

Long Double

-1.7e4932 to +1.7e4932

10

Boolean

1 or 0 (HIGH or LOW)

Char

0 to 255

Table: Chart showing various data types and their essence.

Note: enum, structure are called user defined datatypes


Enum Syntax: enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag.
And value1,value2,....,valueN are values of type type_name and default
values will be 0,1,..
// Changing the default value of enum elements :
enum suit{ club=0; diamonds=10; hearts=20; spades=3; };
//Example of enum
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
//Output: 4 day

Difference between C variable, C array and C structure:


A normal C variable can hold only one data of one
data type at a time.
Eg: int a;
An array can hold group of data of same data type.
Eg: int a[];
A structure can hold group of data of different data
types
Eg: struct student
{
int rollNo;
char name[];
}

C Operators and Expressions


operators: symbols which are used to
perform operations (logical and
mathematical)
operands: variables/constants
operators join constants and variables to
form expressions.
Eg:
expression : A + B * 5
operators : +, *
operands : A, B are variables, 5 is constant

Types of C operators:
1. Arithmetic operators (+,-,/,*,%)
2. Assignment operators (=, + =, - = , * =, /= and %=)
3. Relational operators (< ,<= , > , >= ,= = and != )
4. Logical operators (&&, || and !)
5. Bit wise operators (&, , ^, ~, <<, >>)
6. Conditional/ternary operator (?:)
7. Increment/decrement operators (++,--)
8. Special operators: &, *, sizeof( )

#include <stdio.h>
//Example:
int main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;

Bitwise operator

c = a & b;
/* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b;
/* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b;
/* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a;
/*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );

Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

//C conditional operator


#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);
// If test condition (February == 'l') is true, days equal to 29.
// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;
printf("Number of days in February = %d",days);
return 0;
}
Output:
If this year is leap year, enter 1. If not enter any integer: 1 Number of days in February = 29

How program works?

How to take input in C?


Use: scanf() function defined under stdio.h
#include <stdio.h>
int main()
{
char str1[20], str2[30];
int age;
printf("Enter name: ");
scanf("%s", str1); //Dont allow space
//scanf("%20[0-9a-zA-Z ]", str1); //Allow a-z,A-Z, space
//scanf("%[^\n]s",name); // Allow all character until new line; i.e. end with(^) \n
printf("Enter your age: ");
scanf(%d", age);

printf("Entered Name: %s\n", str1);


printf("Entered Age:%d", &age);
return(0);
}

How to show output to monitor on c: use printf() function


Example:
printf("%c %d %f %e %s %d%%\n", '1', 2, 3.14, 56000000.,"eight", 9);
Output: 1 2 3.140000 5.600000e+07 eight 9%

There are number of format specifiers for printf.


Here are the basic ones :

%d print an int argument in decimal


%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better
%o print an int argument in octal (base 8)
%x print an int argument in hexadecimal (base 16)
%% print a single %

C Control statement
1. C Decision Control statement
a.
b.
c.

if statements
else if ladder statements
nested if statements

2. C Case control statements (used to execute


only specific block of statements in a series of
blocks )
a.
b.
c.
d.

switch
break
continue
goto

If statement example
//Compare 2 variable value
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}

else if ladder statements:


//Take 2 number as input from user and compare them
#include <stdio.h>
int main()
{ int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 >var2)
{
printf("var1 is greater than var2");
}
else if (var2 > var1)
{
printf("var2 is greater than var1");
}
else
{
printf("var1 is equal to var2");
}
return 0;
}

Nested If-else statements

//Take 2 number as input from user and compare them


#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 >var2)
{ printf("var1 is greater than var2");
}
else
{ //Below if-else is nested inside another if-else block
if (var1 <var2)
{ printf("var2 is greater than var1");
}
else
{ printf("var1 is equal to var2");
}
}
return 0;
}

C Loop control statements


Loop control statements in C are used to perform
looping operations until the given condition is
true.
Control comes out of the loop statements once
condition becomes false.
Types of loop control statements in C:
1. for
2. while
3. do-while

Euclids algorithm in C (Using while loop)


#include<stdio.h>
int gcd(int m, int n);
int main()
{
int a,b,result;
printf("Enter two positive integers: ");
scanf("%d %d", &a, &b);
result = gcd(a,b);
printf(The gcd of %d and %d is %d,a,b,result);
return 0;
}
int gcd(int m, int n)
{
int r;
while( (r = m % n) != 0)
{
m = n;
n = r;
}
return n;
}

Euclids algorithm in C (Using for loop)


#include<stdio.h>
int gcd(int m, int n);
int main()
{
int a,b,result;
printf("Enter two positive integers: ");
scanf("%d %d", &a, &b);
result = gcd(a,b);
printf("The gcd of %d and %d is %d",a,b,result);
return 0;
}
int gcd(int m, int n)
{
int r;
for(; (r = m % n) != 0;)
{
m = n;
n = r;
}
return n;
}

//Factorial using recursive function


#include<stdio.h>
int fact(int);
int main()
{
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}
int fact(int n){
if(n==1)
return 1; //base
else
return(n*fact(n-1)); //Recursion logic
}

Euclids algorithm in C (Using Recursive Function)


#include<stdio.h>
int gcd(int m, int n);
int main()
{
int a,b,result;
printf("Enter two positive integers: ");
scanf("%d %d", &a, &b);
result = gcd(a,b);
printf("The gcd of %d and %d is %d,a,b,result);
return 0;
}
int gcd(int m, int n)
{
if (n!=0)
return gcd(n, m%n); // recursion logic
else
return m; //Base condition
}

Continue verses break:


//Continue Example
#include<stdio.h>
int main()
{

for (int j=0; j<=8; j++)


{

//Break Example
#include<stdio.h>
int main()
{

for (int j=0; j<=8; j++)


{

if (j==4)
{
continue;
}

if (j==4)
{
break;
}

printf("%d ", j);


}
}
Output: 0 1 2 3 5 6 7 8

printf("%d ", j);


}
}
Output: 0 1 2 3

Do you know?
C Variable length argument
Variable length arguments is an advanced
concept in C language offered by c99 standard. In
c89 standard, fixed arguments only can be passed
to the functions.
When a function gets number of arguments that
changes at run time, we can go for variable length
arguments.
It is denoted as (3 dots)
stdarg.h header file should be included to make
use of variable length argument functions.

#include <stdio.h>
#include <stdarg.h>
int add(int num,...);
int main()
{
printf("The value from first function call = %d\n", add(2,2,3));// first 2 is total number of arguments
and 2,3 are variable length arguments
printf("The value from second function call= %d \n", add(4,2,3,4,5));// 4 is total number of arguments
2,3,4,5 are variable length arguments
return 0;
}
int add(int num,...)
{
va_list valist;
int sum = 0;
int i;
va_start(valist, num);
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
Output:
va_end(valist);
The value from first function call = 5
return sum;
The value from first function call = 14
}

C Array
is a collection of variables belongings to the same data type.
Array size must be a constant value.
Always, Contiguous (adjacent) memory locations are used to
store array elements in memory.
It is a best practice to initialize an array to zero or null while
declaring, if we dont assign any values to array.
Example for C Arrays:
int a[10];
// integer array
char b[10]; // character array i.e. string
Types of C arrays:
There are 2 types of C arrays. They are,
One dimensional array
Multi dimensional array
Two dimensional array
Three dimensional array, four dimensional array etc

1D - Array
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

*/
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}

//marks array in descending order and find out maximum and minimum
#include<stdio.h>
int main ()
{ int n,i,j,temp=0;
float a[50],max=0,min=0;
printf("How many marks you want to
input?=");
scanf("%i",&n);
printf("Enter %i marks=\n",n);
for(i=0;i<n;i++)
scanf("%f",&a[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{ temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

printf("Marks in descending order:\n");


for(i=0;i<n;i++)
{
printf("%f\n",a[i]);
}
max=a[0];
min=a[n-1];
printf("\nMaximum marks=%f
\nMinimum marks=%f",max,min);
}

//Sort Words in Dictionary Order


#include<stdio.h>
#include <string.h>
int main()
{
int i,j;
char str[10][50],temp[50];
printf("Enter 10 words:\n");
for(i=0;i<10;++i)
gets(str[i]);
for(i=0;i<9;++i)
for(j=i+1;j<10 ;++j)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("In lexicographical order: \n");
for(i=0;i<10;++i)
{
puts(str[i]);
}
}

2D-Array

#include<stdio.h>
int main()
{
int i,j;
// declaring and Initializing array
int c[2][3]={1,3,0,-1,5,9};
//OR
int c[2][3]={{1,3,0}, {-1,5,9}};
//OR
int c[][3]={{1,3,0}, {-1,5,9}};
for (i=0;i<2;i++)
{
for (j=0;j<3;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
}
}
}

//Write a C program to find sum of two matrix of order 2*2 using multidimensional
arrays where, elements of matrix are entered by user.

#include <stdio.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the
help of two for loop. If there was an array
of 'n' dimension, 'n' numbers of loops are
needed for inserting data to array.*/
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{ printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{ printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}

for(i=0;i<2;++i)
for(j=0;j<2;++j){
/* Writing the elements of
multidimensional array using loop. */
c[i][j]=a[i][j]+b[i][j];
/* Sum of corresponding elements of
two arrays. */
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("%.1f\t",c[i][j]);
if(j==1)
/* To display matrix sum in order. */
printf("\n");
}
return 0;
}

C String
C Strings are nothing but array of characters ended with null
character (\0).This null character indicates the end of the
string.
Strings are always enclosed by double quotes. Whereas,
character is enclosed by single quotes in C.
Example for C string:
char string[10] = { a , p , p , l , e, \0}; (or)
char string[10] = apple;
// 10 bytes of memory space is allocated for holding the string
value
(VS)
char string [] = apple;
// memory space will be allocated as per the requirement
during execution

C String functions:
String.h header file supports all the string functions in C language.
All the string functions are given below.
SN String functions
Description
1 strcat ( )
Concatenates str2 at the end of str1.
2 strncat ( )
appends a portion of string to another
3 strcpy ( )
Copies str2 into str1
4 strncpy ( )
copies given number of characters of one string to another
5 strlen ( )
gives the length of str1.
6 strcmp ( )
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0
if str1 > str2.
7 strcmpi_(.)
Same as strcmp() function. But, this function negotiates case. A
and a are treated as same.
8 strchr ( )
Returns pointer to first occurrence of char in str1.
9 strrchr ( )
last occurrence of given character in a string is found
10 strstr ( )
Returns pointer to first occurrence of str2 in str1.

SN
11
12
13
14
15
16
17

String functions
Description
strrstr ( ) Returns pointer to last occurrence of str2 in str1.
strdup ( ) duplicates the string
strlwr ( ) converts string to lowercase
strupr ( ) converts string to uppercase
strrev ( ) reverses the given string
strset ( ) sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given
character
18 strtok ( ) tokenizing given string using delimiter

String Functions Prototype:


short strlen(const char *str);
short strnlen(const char *str, size_t maxlen);
int strcmp(const char *str1, const char *str2);
int strncmp(const char *str1, const char *str2, size_t n);
char *strcat(char *str1, char *str2);
char *strncat(char *str1, char *str2, int n);
char *strcpy( char *str1, char *str2);
char *strncpy( char *str1, char *str2, size_t n);
char *strchr(char *str, int ch);
char *strrchr(char *str, int ch);
char *strstr(char *str, char *srch_term);

//Examples of strlen(), strnlen()


#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Concept";
printf("Length=%d", strlen(str1)); //Output: Length=7
printf("Length when maxlen is 10=%d", strnlen(str1, 10));
// Output: Length when maxlen is 10=7
printf("Length when maxlen is 5=%d", strnlen(str1, 5));
// Output: Length when maxlen is 5=5
return 0;
}

//Examples of strcmp(), strncmp()


#include <stdio.h>
#include <string.h>
int main()
{
int result1,result2;
char s1[20] = "concepts";
char s2[20] = "concepts.COM";
result1 =
/* below it is comparing first 8 characters of s1 and s2*/
result2= strncmp(s1, s2, 8);
printf("Results: result1=%d, result2= %d",result1,result2);
//Output: Results: result1=-1, result2= 0
return 0;
}

//Examples of strcat(), strncat ()


#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Concatenation: %s", s1);//Output: Concatenation: HelloWorld
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation: %s", s1); //Output: Concatenation: HelloWor
return 0;
}

//Examples of strcpy(), strncpy()


#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : Im gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1); //Output: String s1 is: string 2: Im gonna copied into s1
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1); //Output: String s1 is: string 2: Im
return 0;
}

//Examples of strchr(), strrchr(),strstr()


#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = Example of C is fun";
printf ("%s", strchr(mystr, 'f')); //Output: f C is fun
printf ("%s", strrchr(mystr, 'f')); //Output: fun
printf ("%s", strstr(mystr,fu'));//Output : fun
return 0;
}

//Check palindrome of string


Example::
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char s1[30],s2[30];
int i;
puts("Enter any string");
gets(s1);
strcpy(s2,s1);
strrev(s2);
i=strcmp(s1,s2);
if(i==0)
puts("String is palindrome");
else
puts("not a palindrome");
}

//Program to reverse the given word using recursive function


#include<stdio.h>
#include<conio.h>
#include<string.h>
void reverse(char str[],int);
Int main()
{
char *string; //char string[100];
clrscr();
printf("Enter String:");
scanf("%s",string); // gets(string);
reverse(string,strlen(string));
return 0;
}
void reverse(char str[],int len)
{

putchar(str[len]);
if(len>=1)
reverse(str,len-1);
}

C Pointer
C Pointer is a variable that stores/points the address of another variable.
C Pointer is used to allocate memory dynamically i.e. at run time. The pointer
variable might be belonging to any of the data type such as int, float, char, double,
short etc.
Syntax : data_type *var_name;
Example :
int *p; char *p;
// Where, * is used to denote
that p is pointer variable and
not a normal variable.

Key points to remember about pointers in C:


Normal variable stores the value whereas pointer variable stores
the address of the variable.
The content of the C pointer always be a whole number i.e.
address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is
pointing to.
If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are
available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).

//pointer example
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
//ptr= 50; Error : invalid conversion from 'int' to 'int*'
//OR
//ptr= q; Error : invalid conversion from 'int' to 'int*'
ptr = &q; /* address of q is assigned to ptr */
printf("%d", ptr); /* display qs address pointed by ptr variable */
printf("%d", *ptr); /* display qs value using ptr variable */
//NOTE: ptr is also variable which is called pointer and stores address of other
// variable. The address of pointer variable ptr is given by &ptr
printf("%d", &ptr); /* display address of ptr variable */
return 0;
}

//Call by reference = ????


#include<stdio.h>
void swap(int *a, int *b); // function prototype OR function declaration
int main()
{
int m = 22, n = 44;
printf("values before swap m = %d \n and n = %d",m,n);
// swap(m, n); Error : invalid conversion from 'int' to 'int*'
swap(&m, &n); // Calling swap() function by reference
return 0;
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \n and b = %d", *a, *b);
}

Array vs Pointer in C?
Consider and array:
int arr[4];

Here, address of first element of an array is &arr[0] Also, arr represents


the address of the pointer where it is pointing.
Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and value inside address arr are
equal.
Hence, arr[0] is equivalent to *arr
The important difference between them is that, a pointer variable can
take different addresses as value whereas, in case of array it is fixed.
Similarly,
&a[1] equivalent to (a+1) AND, a[1] equivalent to *(a+1).
&a[2] equivalent to (a+2) AND, a[2] equivalent to *(a+2).
&a[3] equivalent to (a+1) AND, a[3] equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

In C, you can declare an array and can use pointer to alter the data of an array.

//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
int main()
{
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
Output::
return 0;
Enter 6 numbers:
}

2
3
4
5
3
4
Sum=21

C Function
Functions are used to improve re-usability,
understandability and to keep track on them.
Types of C functions
1. Library functions in C
2. User defined functions in C

Types of user defined functions:


1.
2.
3.
4.

C function with arguments and with return value


C function with arguments and without return value
C function without arguments and without return value
C function without arguments and with return value

How to call C functions in a program?


1. Call by value
2. Call by reference

Uses of C functions:
C functions are used to avoid rewriting same logic/code again and again in
a program.
There is no limit in calling C functions to make use of same functionality
wherever required.
We can call functions any number of times in a program and from any
place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into
small pieces to achieve the functionality and to improve understandability
of very large C programs.
C function has 3 things :
1. Function declaration or prototype This informs compiler about the
function name, function parameters and return values data type.
2. Function definition This contains all the statements to be executed.
3. Function call This calls the actual function

#include<stdio.h>
/* 1. function declaration or prototype*/
void function1(void);
//OR : 1,2 declaration and definition on same
void main()
place
#include<stdio.h>
{
void function1(void)
........
{
........
........
........
function1(); /* 3. function call */
........
........
}
........
void main()
{
}
........
/* 2. function definition*/
........
void function1(void)
function1(); /* 3. function call */
........
{
........
........
}
........
........
}

// 1. C function with arguments and with return value

#include <stdio.h>
int find_sum(int x, int y);
int main()
{
int a,b,result;
printf("Enter a and b: ");
scanf("%d %d",&a,&b);
result = find_sum(a,b);// 2 arguments a,b and return value stored to result
printf(Sum of %d and %d =%d", a,b,result);
return 0;
}
// return type of the function is int becuase sum of x+y is int
int find_sum(int x, int y)
{
return x+y;
}

// 2. C function with arguments and without return value

#include <stdio.h>
void find_sum(int x, int y);
int main()
{
int a,b,result;
printf("Enter a and b: ");
scanf("%d %d",&a,&b);
find_sum(a,b);// 2 arguments a,b
return 0;
}
// return type of the function is void becuase function is defined without return value
void find_sum(int x, int y)
{
printf(Sum of %d and %d =%d", x,y,x+y);
}

// 3. C function without arguments and without return value

#include <stdio.h>
int find_sum();
int main()
{
int result;
result = find_sum();// No arguments but function return value
printf(%d", result);
return 0;
}
// return type of the function is int becuase sum of a+b is int
int find_sum()
{
int a,b;
printf("Enter a and b: ");
scanf("%d %d",&a,&b);
printf(Sum of %d and %d =", a,b);
return a+b;
}

// 4. C function without arguments and with return value

#include <stdio.h>
void find_sum();
int main()
{
find_sum(); // no argument is passed to find_sum()
return 0;
}
// return type of the function is void becuase no value is returned from the function
void find_sum()
{
int a,b,result;
printf("Enter a and b: ");
scanf("%d %d",&a,&b);
result = a+b;
printf(Sum of %d and %d =%d", a,b,result);
}

User defined Function: Which approach is better?

Well, it depends on the problem you are trying to


solve.
In case of this problem, the last approach is
better.
A function should perform a specific task.
The find_sum() function doesn't take input from
the user nor it displays the appropriate message.
It should take two arguments a and b and return
the sum; (i.e. function with argument and with
return value)
Function makes code modular, easy to
understand and debug.

How to call C functions in a program?


There are two ways that a C function can be called from a program. They
are,
1. Call by value
2. Call by reference
1. Call by value:
In call by value method, the value of the variable is passed to the function
as parameter.
The value of the actual parameter can not be modified by formal
parameter.
Different Memory is allocated for both actual and formal parameters.
Because, value of actual parameter is copied to formal parameter.
Note:
Actual parameter This is the argument which is used in function call.
Formal parameter This is the argument which is used in function
definition

include<stdio.h>
void swap(int a, int b);

Example program for C function (using call by value):


In this program, the values of the variables m and n
are passed to the function swap.
These values are copied to formal parameters a and
b in swap function and used.

int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n); // m and n are actual parameter
}
void swap(int a, int b) // a and b are formal parameter
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}

2. Call by reference:
In call by reference method, the address of the
variable is passed to the function as parameter.
The value of the actual parameter can be modified
by formal parameter.
Same memory is used for both actual and formal
parameters since only address is used by both
parameters.

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
Example program for C function (using call by
return 0;
reference):
}
In this program, the address of the variables m and n
are passed to the function swap.
//Understand this deeply
These values are not copied to formal parameters a
void swap(int *a, int *b)
and b in swap function.
{
Because, they are just holding the address of those
int tmp;
variables.
tmp = *a;
This address is used to access and change the values of
*a = *b;
the variables.
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

Key points to remember while writing functions in C:


All C programs contain main() function which is mandatory.
main() function is the function from where every C program is started to
execute.
Name of the function is unique in a C program.
There can any number of functions be created in a program ( no limit ).
All functions are called in sequence manner specified in main() function.
One function can be called within another function.
C functions may or may not return values to calling functions.
When a function completes its task, program control is returned to the
function from where it is called.
Before calling and defining a function, we have to declare function prototype
in order to inform the compiler about the function name, function
parameters and return value type.
C function can return only one value to the calling function.
When return data type of a function is void, then, it wont return any values
When return data type of a function is other than void such as int, float,
double, it returns value to the calling function.

C Arithmetic functions
C functions which are used to perform
mathematical operations in a program are
called Arithmetic functions.
Example :
abs(), floor(), round(), ceil(), sqrt(), exp(), log(),
sin(), cos(), tan(), pow() and trunc()
math.h and stdlib.h header files support
all the arithmetic functions in C language.

C Library functions
Library functions in C language are inbuilt functions which are
grouped together and placed in a common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined
output instead of writing our own code to get those outputs.
These library functions are created by the persons who designed
and created C compilers.
1.stdio.h : This is standard input/output header file in which
Input/Output functions are declared
2.conio.h : This is console input/output header file
3.string.h : All string related functions are defined in this header file
4.stdlib.h : This header file contains general functions used in C
programs
5.math.h : All maths related functions are defined in this header file
6.time.h : This header file contains time and clock related functions

C Creating custom library functions


Step:1. New Project

Step:2. Choose Console Application, Select C Project; Put project name and press Ok

Step:3. Choose folder (create any new folder; here I make MySystem) and click Save

Step:4. Right click on Project name and click New File

Step:5. Type your function prototypes as below:

Step:6 Save Header file as helper.h

Step:7 Create new file and write function definition (Do not forget to include helper.h
where function prototype was defined)

Step:8 Save it as helper.c in same folder

Step:8 Now, write your main program where you can include helper.h and use its functions.

Summary:
Steps for making custom library in C.

C Dynamic memory allocation


Dynamic memory allocation in C:

The process of allocating memory during program


execution is called dynamic memory allocation.
Dynamic memory allocation functions in C:
C language offers 4 dynamic memory allocation functions.
They are,
1. malloc()
2. calloc()
3. realloc()
4. free()

Syntax of malloc():
ptr=(cast-type*)malloc(byte-size)
ptr=(int*)malloc(100*sizeof(int));
Syntax of calloc():
ptr=(cast-type*)calloc(n,element-size);
ptr=(float*)calloc(25,sizeof(float));

Syntax of realloc():
ptr=realloc(ptr,newsize);
syntax of free():
free(ptr);

1. malloc() function in C:
malloc () function is used to allocate space in memory during the execution of program.
malloc () does not initialize the memory allocated during execution & carries garbage value.
malloc () function returns null pointer if requested amount of memory not available
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
mem_allocation = (char*)malloc( 20 * sizeof(char) ); /* memory is allocated dynamically */
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation," dynamic memory ");
}
printf("Dynamically allocated memory content : %s\n", mem_allocation );
free(mem_allocation);
}

2. calloc() function in C:
calloc () function is also like malloc () function. But calloc () initializes the allocated
memory to zero. But, malloc() doesnt.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
mem_allocation = (char*) calloc( 20, sizeof(char) ); /* memory is allocated dynamically */
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"dynamic memory");
}
printf("Dynamically allocated memory content : %s\n", mem_allocation );
free(mem_allocation);
}

3. realloc() function in C:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to
new size.
If enough space doesnt exist in memory of current block to extend, new block is allocated
for the full size of reallocation, then copies the existing data to new block and then frees the
old block.
#include <stdio.h>
#include <stdlib.h>

int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf(\n Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
Output:
scanf("%d",&n2);
Enter size of array: 3
Address of previously allocated memory:
ptr=(int*)realloc(ptr,n2);
3309488 3309492 3309496
for(i=0;i<n2;++i)
Enter new size of array: 2
printf("%u\t",ptr+i);
3309488 3309492

4. free() function in C:
free () function frees the allocated memory by malloc (), calloc
(), realloc () functions and returns the memory to the system.

Difference between static memory allocation and dynamic


memory allocation in C:

S.No.

Static memory allocation

Dynamic memory
allocation

1.

In static memory allocation, memory is allocated


In dynamic memory
while writing the C program. Actually, user requested allocation, memory is
memory will be allocated at compile time.
allocated while executing
the program. That means at
run time.

2.

Memory size cant be modified while execution.


Example: array

Memory size can be


modified while execution.
Example: Linked list

//Write a C program to find sum of n elements entered by user:


#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum=sum+ *(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

C Structure
C Structure is a collection of different data types
which are grouped together and each element in
a C structure is called member.
If you want to access structure members in C,
structure variable should be declared.
Many structure variables can be declared for
same structure and memory will be allocated for
each separately.
It is a best practice to initialize a structure to null
while declaring, if we dont assign any values to
structure members.

Below table explains following concepts in C structure.


How to declare a C structure?
How to initialize a C structure?
How to access the members of a C structure?

Type

Using normal variable

Using pointer variabe

Example

struct student
{
int mark;
char name[10];
float average;
};

struct student
{
int mark;
char name[10];
float average;
};

Declaring
structure variable

struct student report;

struct student *report,


rep;

Initializing
structure variable

struct student report =


{100, Mani, 99.5};

struct student rep = {100,


Mani, 99.5};
report = &rep;

Accessing
structure members

report.mark
report.name
report.average

report -> mark


report -> name
report -> average

Example program for C structure:


#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record = {0}; //Initializing to null
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;

//Example program Another way of declaring C structure:


#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
} record;
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

//C structure declaration in separate header file:


//File name - structure.c
#include <stdio.h>
#include <string.h>
#include "structure.h" /* header file where C structure is declared */
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Uses of C structures:
C Structures can be used to store huge data. Structures act
as a database.
C Structures can be used to send data to the printer.
C Structures can interact with keyboard and mouse to store
the data.
C Structures can be used in drawing and floppy formatting.
C Structures can be used to clear output screen contents.
C Structures can be used to check computers memory size
etc.

C Typedef
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program.
This is same like defining alias for the commands.
Consider the below structure.
struct student
{
int mark [2];
char name [10];
float average;
}
Variable for the above structure can be declared in two ways.
1st way :
struct student record;
/* for normal variable */
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;
An alternative way for structure declaration using typedef in C:
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
To declare structure variable, we can use the below statements.
status record1;
/* record 1 is structure variable */
status record2;
/* record 2 is structure variable */

//example program for C typedef:


#include <stdio.h>
#include <limits.h>
int main()
{
typedef long long int LLI;

Output:
Storage size for long long int data type : 8

printf("Storage size for long long int data " \


"type : %ld \n", sizeof(LLI));

return 0;
}
/*
typedef long long int LLI;
In above statement, LLI is the type definition for the real C command long long int.
We can use type definition LLI instead of using full command long long int in a C
program once it is defined.
*/

static variable in C:
Static variables retain the value of the variable between different function calls.

//without static example

//static example

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

Output: 0 0 0 0

Output: 0 1 2 3

extern variable in C
The scope of this extern variable is throughout the main program. It is
equivalent to global variable.
Definition for extern variable might be anywhere in the C program.
That means declare in one file and access in other file of same program
#include<stdio.h>
int x = 10 ;
int main( )
{

extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;

register variable in C:

Register variables are also local variables, but stored in register memory. Whereas, auto variables are
stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are stored in register
memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64
bits)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output:
for (i=0;i<5;i++)
value of arr[0] is 10
{ // Accessing each variable
value of arr[1] is 20
printf("value of arr[%d] is %d \n", i, arr[i]);
value of arr[2] is 30
}
value of arr[3] is 40
return 0;
value of arr[4] is 50
}

C Miscellaneous functions
//rand() : Returns random integer number range from 0 to at
least 32767
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main ()
{
printf ("1st random number : %d\n", rand() % 100);
printf ("2nd random number : %d\n", rand() % 100);
printf ("3rd random number: %d\n", rand());
return 0;
}

You might also like