C - Programming & Mat Lab Unit-1
C - Programming & Mat Lab Unit-1
C Programming Basics
Introduction
C is a programming language developed at AT’s &T’s BELL laboratories of USA in 1972.
It was designed and written by a man named ”DENNIS RITCHE”.
C is a general purpose computer programming language.
It was used in operating systems, devices drives, but used in a wide range of application domains.
C is commonly used on computer architectures that range from the largest supercomputers to the
smallest microcontrollers and embedded systems.
C programming is mainly used to develop UNIX Operating System.
C was originally developed at Bell, to construct uitilities running on Unix.
It was applied to re-implementing the kernel of Unix Operating System.
C programming is considered as the base for the programming languages. So it is called as Mother
Language.
Mother Language :
C Programming Language is considered as mother Language for all the modern Programming Languages. Because, most
of the compilers like JVMS, kernels, etc.. are written in C Language and also most of the programming language follows C
syntax. Eg: C++, Java, c#..etc.
C Language is used to create system software. Because, it can be used to do low-level programming and also used to
create hardware devices, os drivers, kernals, etc...
C is a procedural programming language. Procedure is known as function, method, routine, subroutine. Procedural
language specifies a series of steps for the program to solve the program.
It is a subset of procedural programming language. Structure means to break a program into parts or blocks .So that it
may be easy to understand. In c program, we break the program into parts by using functions. It makes program easier
to understand and modify.
Features of C Programming :
Simple
Recursion
Memory Management
Fast & Efficient
Modularity
General Purpose Language
Rich set of built in operations
Portability
Easy to extend
Rich in libraries
Middle level language
Statically type
Characteristics:
Small Size
Extensive use of function calls
Structured language
Powerful programming language
Portability
Case Sensitive
Applications of C language:
C language is used to create computer application software like Databases, Spreadsheets.
Used to create system software as Operating systems.
To create applications related to graphics like computer & mobile game.
UNIX kernel has been fully developed in cLanguage.
Used to create Network devices & Device drivers.
Used to make a compiler.
Syntax:
Header files
Main method()
{
Statement 1;
Statement 2;
return 0;
}
// Basic program
#include<stdio.h>
#include<conio.h>
void main()
{
printf(“hello world”);
return 0;
}
Output: hello world
History
The root of all modern language is ALGO (Algorithmi c language),it is first computer programming language to
use block structure.
MARTIN RICHARDS developed a language called “BCPL” (Basic combined programming language).It is
derived from “ALGO”.
In 1970 kenThompson created “B” language by using BCPL.
Both BCPL & B programming languages were typeless.
After this “C” was developed using ‘BCPL’ & ’B’ by Dennis Ritchie at the bell lab in1972.
C program can be viewed as a group of building blocks called functions. A function is a subroutine that may
include one or more statements designed to perform a specific task.
There is a specific structure to start the programming in c language. Without structure it is difficult to analyze the
program and the solution. It gives the basic idea of the order of the sections in a program, when and where to
use a particular statements, variables, functions, curly braces and parenthesis.
Document Section
Link Section
Deceleration Section
Executable Section
}
Function1
Function2
Function3
Document Section:
The Documentation Section Consist of a set of comment lines giving the name of the program, the author
and other details, which the programmer would like to use latter.
Global Declaration:
This is the section where variable are declared globally so that it can be access by all the functions used in the
program. And it is generally declared outside the function
Main():
It is the user defined function and every function has one main()function from where actually program is started
and it is encloses within the pair of curly braces. The main( ) function can be anywhere in the program but in
general practice it is placed in the first position.
Syntax:
main()
{……..
……..
……..
}
The main( )function return value when it declared by data type as
int main( )
{
Return 0
The main function does not return any value when void(means null/empty)as void main(void) or void main()
printf(“C language”);
Output: C language
The program execution start with opening braces and end with closing brace. And in between the two braces declaration
part as well as executable part is mentioned. And at the end of each line, the semi-colon is given which indicates statement
termination.
#include<stdio.h>
return 0;
Characters that are typically available on most keyboards and character encoding.
Keywords
There are certain words reserved for doing specific task, these words are known as reserved word or keywords.
These words are predefined and always written in lower case or small letter. These keywords cann’t be used as
a variable name as it assigned with fixed meaning .C language supports 32 key words, Some examples are:
Data Types
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer,
character, floating, double, etc. Each data type requires different amounts of memory and has some specific
operations which can be performed over it. The data type is a collection of data with values having fixed values,
meaning as well as its characteristics.
Primitive or Primary Data Types : Primitive data types are the most basic data types that are used
for representing simple values such as integers, float, characters, etc.
User Defined Data Types: The user-defined data types are defined by the user himself.
Derived Types : The data types that are derived from the primitive or built-in data types are referred
to as Derived Data Types.
Primitive data type Integer ,character ,floating point, Double floating point, void.
User defined data type Structure ,Union, Enum, Typedef.
Derived data type Function ,Pointer ,Array
Syntax of Integer: We use int key word to declare the integer variable:
int var_name;
The integer data type can also be used as
1. Unsigned int: Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to
32,767.
3. Long int: Larger version of the int data types can store values greater than int.
4. Unsigned short int: Similar in relationship with short int as unsigned int with int
Character data type allows its variable to store only a single character.
The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
Range:(-128to127)or(0to255)
Size:1byte
Format Specifier:%c
Syntax of char
The char keyword is used to declare the variable of character type:
Char var_name;
// C program to print Integer data types.
#include <stdio.h>
int main()
{
char a='a';
char c;
printf("Value of a:%c\n", a);
a++;
printf("Value of a after increment is:%c\n",a);
//c is assigned ASCII values which corresponds to the character 'c’ a-->97 b-->98 c99 here c will be printed c = 99;
printf("Value of c:%c", c);
return 0;
}
Output
Value of a: a
Value of a after increment is :b
Value of c: c
Float Data Type
In C programming float data type is used to store floating-point values. Float in C is used to store decimal and
exponential values. It is used to store decimal numbers (numbers with floating point values) with single
precision.
Range:1.2E-38to 3.4E+38
Size:4 bytes
Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
Float var_name;
//C Program to demonstrate use of Floating types
#include<stdio.h>
int main()
{ float a=9.0f;
float b =2.5f; // 2x10^-4
floatc=2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
}
Output
9.000000
2.500000
0.000200
}
Double Data Type:
A Double data type in C is used to store decimal numbers (numbers with floating point values) with double precision. It
is used to define numeric values which hold numbers with decimal values. It can easily accommodate about 16 to17
digits after or before a decimal point.
Range:1.7E-308to1.7E+308
Size:8 bytes
Format Specifier : %lf
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;
//C Program to demonstrate use of double data type
#include <stdio.h>
int main()
{
double a=123123123.00;
double b = 12.293123;
double c =2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c); return 0;
}
Output
123123123.000000
12.293123
2312312312.123123
Derived DataTypes
Derived data types give the programmer the ability to handel heterogeneous data, directly modify
memory and build complicated data structures.
Derived data types are classified as:
1. Arrays
2. Functions
3. Pointers
4. Structure
Arrays : Arrays are used to store multiple values in a single-variable, instead of declaring separate variables, It
provides a mechanism for joining multiple targets of the same data type under the same name.
Index is used to access the elements of an array the size of array is fixed at declaration time and it cannot be
changed.
Pointers: A pointer is a derived data type that keep strackofanother data type's memory address. When
a pointer is declared, the data type it refers to is stated first,and then the variable name is preceded by
an asterisk (*).
Data type asterisk(*) variable name;
Structure : Structure allows group of many data types under a single name .It gives you the ability to
create your own unique data structures.
The data types that are defined by the user are called the user defined data types.
These are classified into 4 types.
1. Structure
2. Union
3. Enumerations
4. Typedef
Structure: A Structure is a user defined data type in ‘c’. A structure creates a data type that can be used to group of
items of possibly different types into a single type. It store in different memory.
1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
A structure's members can be accessed by using the dot (.) operator.
#include <stdio.h>
#include<strings.h>
struct person
charname[50];
int citno;
floatsalary;
person1;
int main ()
{
Strcpy (person1.name,“ram”);
person1.citno = 1984;
person1.salary = 25000;
printf(“Name:%s\n”,person1.name);
printf(“Citizenship:%d\n”,person1.citno);
printf(“Salary : %f\n”,person1.salary);
return 0;
Out put
Name: Ram
Citizenship: 1984
Salary: 2500.00
Union
Union are similar to structures it is also collection of different data items, but with a common memory. A
derived data type called a union enables you to store various data types in the same memory address. In
contrast to structures, where each member has a separate memory space, members of a union all share a single
memory space. A value can only be held by one member of a union at any given moment. When you need to
represent many data types interchangeably, unions come inhandy. Like structures, you can access the members
of a union by using the dot (.) operator.
#include<stdio.h>
union job;
float salary;
int id;
J;
int main()
{
J.salary=20000;
J.id=15;
printf(“%f\n”, J.salary);
printf(“%d\n”, J.id);
return 0;
Enumerations: A set of named constants or enumerators that represent a collection of connected values
can be defined in C using the enumeration datatype(enum). Enumerations give you the means to given a
mesthat make sense to a group of integral values, which makes your code easier to read and maintain.
Enumerations are mainly used to assign names to integrals constants, the names makes a program easy to read
and maintain.
#include<stdio.h>
enum week
int main ( )
day = wed;
printf(“%d”,day);
return 0;
Output :2
Typedef: typedef is a keyword used in c programming to provide some meaningful name to the already
existing variable in c program it is like alias name.
We can say that this keyword is used to redefine the name of already existing variable.
Typedef longlongll;
int main ( )
ll var = 20;
printf(“%d”, var);
return 0;
Out put:20
Constants
Constant is a any value that cannot be changed during program execution. In C, any number, single character, or
character string is known as a constant. A constant is an entity that doesn’t change where as a variable is an
entity that may change.
For example, the number 50 represents a constant integer value. The character string "Programming in C
is fun.\n" is an example of a constant character string.
Syntax:
Defining the constants :there are two ways to define the constants. They are
1. Const keyword
2. #define preprocessor
Const keyword: by using the keyword const we can declare the constants.
#include<stdio.h>
int main()
{
Const float pi=3.14;
printf(“the value of pi is:%f”,pi);
return 0;
}
Output
The value of pi is :3.14
Types of Constants:
Basically there are two types of constants they are: Numeric constant
Character constant
Numeric constant: Numeric constant consists of digits. It required minimum size of 2bytes and max 4bytes. It
may be positive or negative but by default sign is always positive. No comma or space is allowed within the
numeric constant and it must have at least 1 digit.
Integer constant
An integer constants are whole number which have no decimal point. Types of integer constants
are: Decimal constant: 0 9(base 10)
Octal constant:0--------7(base 8)
Hexa decimal constant:0----9,A ------- F(base16)
Binary constant:0&1(base 2)
Real/floating constant
Real constant is also called floating point constant.
To construct real constant we must follow the rule of,
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within are all constant.
Ex.: +325.34 426.0 -32.76
A character constant is written as one character within single quotes such as‘a’.The value of a character constant
is the numerical value of the character in the machines character set.
There are 4types of constants:
1. Single Character Constant :A character which has been specified in a single quotes.
Eg : ‘A’, ‘7’, ‘$’
#include<stdio.h>
int main ()
{
Char ch=‘a’;
printf(“character constant is:%c\n”, ch);
return 0;
}
2. String Character Constant: A group of characters which are enclosed with double quotes.
Eg: “hello” , “5+0”, “ hello world”.
3. Backslash Character Constant: Backslash characters which are executed directly by compiler.
Eg : \n – new line.
\t–horizontal tab
\v-vertical tab
\r-carriage return
4. Enumeration Character Constant : Enumeration constants are user defined constants created using‘enum’
keyword. They are often used to create sets of named integer constants.
Eg: enumdays{ Sunday,Monday}.
Variables
Variable is a data name which is used to store some data value or symbolic names for storing program computations
and results. The value of the variable can be change during the execution. The rule for naming the variables is same as
the naming identifier. Before used in the program it must be declared. Declaration of variables specify its name, data
types and range of the value that variables can store depends upon its data types.
int-stores interger
char–stores single characters
Syntax:
For eg:
int a= 15;
int my_num=20;
float f=0.98;
char c = ‘ a’;
Rules for creating a variable:
#include<stdio.h>
int main()
{
//creating variables
Output:
15
15.89
k
#include<stdio.h>
int main()
{
int mynum=13;
mynum = 34;
printf(“%d”,mynum);
return 0;
}
Output:34
#include<stdio.h>
int main()
{
int a=14;
int b=56;
a = b;
printf(“%d”,a);
return 0;
}
Output:56
//program for multiple variables
#include<stdio.h>
int main()
{
int x=5,y=8,z=6;
printf (“%d”, x+y+z);
return 0;
}
Output:19
Types of Variable in C:
Local Variable
Local variable in c is a variable that is declared inside a function or a block of code. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside their
own. Its scope is limited to the block or function in which it is declared.
#include<stdio.h>
void function ( )
{
int x= 10;
//local variable #include<stdio.h>
printf(“%d”, x); int main()
} {
int main() (or) int x= 10;
{ printf(“%d”, x);
function(); }
}
Output: 10
Output:10
Global Variable:
A global variable in c is a variable that is declared outside the function or a block of code.usually on top of the
program. Global variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program. A global variable can be accessed by any function.
Its scope is the whole program.
#include<stdio.h>
int x = 10;
void function1()
{
printf(“%d\n”, x);
}
void function2()
{
printf(“%d\n”, x);
}
int main()
{
function1 ();
function2 ();
}
Output:10
10
Static Variable:
Static variable in C is a variable that is defined using the static keyword. It can be defined only once in a C
program and its scope depends upon the region where it is declared.( can be global or local)
Syntax:
#include<stdio.>
void function1()
{
int x = 10;
static int y=20;
x = x + 1;
y=y+1;
printf(“%d%d”, x,y);
}
int main()
{
function1();
}
Output :1121
#include<stdio.h>
void function ( )
{
int x= 20;
static int y=30;
x = x+10;
y=y+10;
printf(“\t local:%d\n\t static:%d\n”, x,y);
}
int main()
{
printf (“ first call \n”);
function ( );
printf(“Second call\n”);
function ( );
printf(“Third call\n”);
function ( );
}
Output:
Firstcall
local:20
static:30
Second call
local:20
static:40
Third call
local:20
static:50
Note: local variable print the same value for each function call but, static will print incremented value.
Automatic variable
All the local variables are automatic by default ,They are also known as auto variables. Their scope is local and
their lifetime is till the end of the block. We can use‘ auto’ keyword to define the auto variables . The default
value of the auto variables is a garbage value.
Syntax:
auto datatype variablename=value;
#include<stdio.h>
void function ( )
{
int x=10;
auto int y=20;
printf(“Auto variable:%d”, y);
}
int main()
{
function ();
return 0;
}
Output:20
External variable:
External variable can be shared between multiple C files. We can declare an external variable using the extern
keyword. Their scope is global.
Syntax
#include<stdio.h>
extern int x = 10;
int main ( )
{
printf(“%d”,x);
return0;
}
Output:10
ArithmeticOperator
This operator used for numeric calculation. And these operators are addition, subtraction, multiplication, division.
Binary arithmetic operator on other hand required two operand and its operators are
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus).
But module scan not applied with floating point operand as well as there are no exponent operator in c.
Symbol Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Program
#include<stdio.h>i
nt main ( )
{
inta=20,b=10;
printf(“%d\n”,a+b); output:30
printf(“%d\n”,a-b); 10
printf(“%d\n”,a*b); 200
printf(“%d\n”,a/b); 2
printf(“%d\n”,a%b); 0
return 0;
}
Evaluation of Compound Expressions
Compound Expression: A compound expression is a series of simple expressions joined by arithmetic operators. A simple
expression used in a compound expression must return a numeric value.
Program
#include<stdio.h>
int main ()
{
int a=20, b=10,c=15, d=5, e;
e = (a+b)*c/d;
printf(“value of (a+b)*c/d is:%d\n”, e);
e= ((a+b)*c)/d;
printf(“value of ((a+b)*c)/d is:%d\n”, e);
e = (a+b)*(c/d);
printf(“value of (a+b)*(c/d)is:%d\n”, e);
e = a+(b*c)/d;
printf(“value of a+(b*c)/d is:%d\n”, e);
reurn 0;
}
Output :
value of (a+b)*c/d is : 90
value of(a+b)*c)/d is:90
value of (a+b)*(c/d) is:90
value of a+(b*c)/d is:50
Assignment Operator
Assignment operator are used to assign the result of an expression to a variable. Operand on the left hand side should
be variable and the operand on the right hand side should be variable or constant or any expression.
When variable on the left hand side is occur on the right hand side then we can avoid by writing the compound
statement.
SYNTAX: Var=value;
For example:
int x=y;
int sum=x+y+z;
Program
#include<stdio.h>
int main ( )
{
int a=10;
printf(“%d\n”,a); Output: 10
printf(“%d\n”,a+=10;); 20
return 0;
}
a=a+10
=10+10
a=20
Nested Assignment
If more than one assignment operator is present in statement, then that statement is called nested assignment statement.
Output:Z=11 Output:Z=10
a=11 a= 11
Decrement Operators
It is used to decrement the value by 1.It is categories into pre decrement and post decrement.
Pre decrement
Decrement operator is placed before the operand and the value is first decremented and then operation or
expression is performed on it.
Ex:z=--a
a=a-1
z=a
Post Decrement
Decrement operator is placed after the operand and the value is decremented after the operation. Ex:
z=a—
z=a
a=a-1
Program
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int a=10,Z; int a=10,Z;
Z=--a; Z=a--;
printf(“Z=%d\n”,Z); printf(“Z=%d\n”,Z);
printf(“a=%d\n”,a); printf(“a=%d\n”,a);
} }
Output:Z=9 Output:Z=10
a=9 a=9
Program
#include<stdio.h>
int main ()
Double x=1.2;
int sum=(int)x+1;
printf(“sum=%d”,sum);
return 0;
Output:
Sum=2
Relational Operator
It is use to compared value of two expressions depending on their relation. Expression that contain relational
operator is called relational expression.
The value or result of a relational expression is either true or false
Ex:45>58 False(0)
34==24+10 True(1)
Operator Meaning
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
== equal to
!= Not equal to
Program
#include<stdio.h>
#include<math.>
int main ()
{
int a=10,b=20;
printf(“%d\n”,a<b); Output:1
printf(“%d\n”,a>b); 0
printf(“%d\n”,a<=b); 1
printf(“%d\n”,a>=b); 0
printf(“%d\n”,a==b); 0
printf(“%d\n”,a!=b); 1
return 0;
}
Operator Precedence
Precedence
Precedence simply means that which operation is going to perfom first and which is going to perform last in that
expression.
Array subscript []
1
Dot operator(structure &union member .
access)
Logiacal Operator
Operator used with one or more operand and return either value zero(for false) or one (for true). The operand may
be constant, variables or expressions. And the expression that combines two or more expressions is termed as logical
expression.
C has three logical operators:
Where logical NOT is a unary operator and other two are binary operator. Logical AND gives result true if both
the conditions are true, otherwise result is false. And logical OR gives result false if both the condition false,
otherwise result is true.
Program
#include<stdio.h>
int main ( )
{
inta=10,b=20,c=30;
printf(“%d\n”,(a>b)&&(a<c)); Output:0
printf(“%d\n”,(a>b)||(a<c)); 1
printf(“%d\n”,!(a>b)); 0
return 0;
}
Bitwise Operator
Bitwise operator permit programmer to access and manipulate of data at bit level. Various bitwise operator
enlisted are
one's complement(~)
bitwise AND (&)
bitwise OR ( | )
bitwise XOR ( ^ )
#include<stdio.h>
int main ()
{
int a=12,b=10;
printf(“%d\n”, a&b);
printf(“%d\n”, a|b);
printf(“%d\n”, a^b);
return 0;
}
Output:8
14
6