Concepts of Programming (Using C)
Concepts of Programming (Using C)
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
-32768 to +32767
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
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 Control statement
1. C Decision Control statement
a.
b.
c.
if statements
else if ladder statements
nested if statements
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;
}
//Break Example
#include<stdio.h>
int main()
{
if (j==4)
{
continue;
}
if (j==4)
{
break;
}
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;
}
}
}
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
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.
//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;
}
Array vs Pointer in C?
Consider and array:
int arr[4];
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
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 */
........
{
........
........
}
........
........
}
#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;
}
#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);
}
#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;
}
#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);
}
include<stdio.h>
void swap(int a, int b);
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);
}
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
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:7 Create new file and write function definition (Do not forget to include helper.h
where function prototype was defined)
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.
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.
S.No.
Dynamic memory
allocation
1.
2.
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.
Type
Example
struct student
{
int mark;
char name[10];
float average;
};
struct student
{
int mark;
char name[10];
float average;
};
Declaring
structure variable
Initializing
structure variable
Accessing
structure members
report.mark
report.name
report.average
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 */
Output:
Storage size for long long int data type : 8
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.
//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;
}