INTRODUCTION TO C
Basics of ‘C’
By Swathi Sridharan
Asst. Prof. Dept,ISE
BNMIT
INTRODUCTION TO C
Programming languages
• Various programming languages
• Some understandable directly by computers
• Others require translation steps
1. Machine language
• Natural language of a particular computer
• Consists of strings of numbers(1s, 0s)
• Instruct computer to perform elementary
operations one at a time
• Machine dependent
2. Assembly Language
• English like abbreviations
• Translators programs called Assemblers to
convert assembly language programs to machine
language.
• E.g. add overtime to base pay and store result in
gross pay
• LOAD BASEPAY
• ADD OVERPAY
• STORE GROSSPAY
3. High-level languages
• To speed up programming even further
• Single statements for accomplishing substantial
tasks
• Translator programs called Compilers to convert
high-level programs into machine language
• E.g. add overtime to base pay and store result in
gross pay
grossPay basePay overtimePay
Before C?
• Evolved from two previous languages
• BCPL , B
• BCPL (Basic Combined Programming Language) used
for writing OS compilers
• B used for creating early versions of UNIX OS
• Both were typeless languages
• C language evolved from B
• Typeless no datatypes.
• Every data item
occupied 1 word in memory.
• In 1983, the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C.
• The resulting definition, the ANSI standard, or ANSI C, was completed late
1988.
GENERAL ASPECT OF ‘C’
• C is a High level , general –purpose structured
programming language. Instructions of C
consists of certain English keywords such as if,
else, for ,do and while
• C contains certain additional features that
allows it to be used at a lower level , acting as
bridge between machine language and the
high level languages.
• This allows C to be used for system
programming as well as for applications
programming
Development with C
4 stages
• Editing Writing the source code by using some
IDE or editor
• Preprocessing or libraries Already available
routines
• compiling translates or converts source to
object code for a specific platform source
code- object code
• linking resolves external references and
produces the executable module
• Portable programs will run on any machine but..
• Note! Program correctness and robustness are most
important than program efficiency
THE CHARACTER SET OF ‘C’
• C language consist of some characters set, numbers and some
special symbols.
• The character set of C consist of all the alphabets of English
language.
• C consist of Alphabets a to z, A to Z
• Numeric 0 to 9
• Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more
• The words formed from the character set are building blocks of C
and are also known as tokens.
• These tokens represent the individual entity of language.
• The following different types of token are used in C
1) Identifiers 2)Keywords 3)Constants
4) Operators 5)Punctuation Symbols
Identifiers
• A 'C' program consist of two types of elements , user defined
and system defined.
• Idetifiers is nothing but a name given to these elements.
• An identifier is a word used by a programmer to name a
variable , function, or label.
• identifiers consist of letters and digits, in any order, except
that the first charecter or lable.
• Identifiers consist of letters and digits if any order,except that
the first charecter must be letter.
• Both Upper and lowercase letters can be used
Keywords
• Keywords are nothing but auto double int struct
system defined identifiers.
break else long switch
• Keywords are reserved words
of the language. case enum register typedef
• They have specific meaning in
the language and cannot be char extern return union
used by the programmer as
variable or constant names const float short unsigned
• C is case senitive, it means
continue for signed void
these must be used as it is
• 32 Keywords in C default goto sizeof volatile
Programming
do if static while
Variables
• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. There are following basic variable
types −
Type Description
• char Typically a single octet(one byte). This is an integer type.
• int The most natural size of integer for the machine.
• float A single-precision floating point value.
• double A double-precision floating point value.
• void Represents the absence of type.
Constants
• A constant is a value or an identifier whose value cannot be altered
in a program. For example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg.
const double PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is
same for this program.
Integer constants
• A integer constant is a numeric constant (associated with number)
without any fractional or exponential part. There are three types of
integer constants in C programming:
• decimal constant(base 10)
• octal constant(base 8)
• hexadecimal constant(base 16)
Constants
Floating-point constants
• A floating point constant is a numeric constant that has either
a fractional form or an exponent form. For example:
2.0,0.0000234,-0.22E-5
Character constants
• A character constant is a constant which uses single quotation
around characters. For example: 'a', 'l', 'm', 'F'
String constants
• String constants are the constants which are enclosed in a pair
of double-quote marks. For example: "good" ,"x","Earth is
round\n"
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special
meaning in C programming. For example: newline(enter), tab, question mark etc.
In order to use these characters, escape sequence is used.
• For example: \n is used for newline. The backslash ( \ ) causes "escape" from the
normal way the characters are interpreted by the compiler.Escape
Sequences Character
• \b Backspace
• \f Form feed
• \n Newline
• \r Return
• \t Horizontal tab
• \v Vertical tab
• \\ Backslash
• \' Single quotation mark
• \" Double quotation mark
• \? Question mark
• \0 Null character
Operators in C:An operator is a symbol which operates on a value or a
variable. For example: + is an operator to perform addition.
C programming has wide range of operators to perform various
operations. For better understanding of operators, these
operators can be classified as:
• Arithmetic Operators
• Increment and Decrement Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Bitwise Operators
• Special Operators
Arithmetic Operator
• Operator Meaning of Operator
• + addition or unary plus
• - subtraction or unary minus
• * multiplication
• / division
• % remainder after
division( modulo division)
Increment and Decrement Operators
1. C programming has two operators increment ++
and decrement -- to change the value of an operand
(constant or variable) by 1.
2. Increment ++ increases the value by 1 whereas
decrement -- decreases the value by 1.
3. These two operators are unary operators, meaning
they only operate on a single operand.
eg. int a=10, b=100
++a = 11
--b = 99
C Assignment Operators
• An assignment operator is used for assigning a value
to a variable. The most common assignment
operator is =
• Operator Example Same as
• = a=b a=b
• += a += b a = a+b
• -= a -= b a = a-b
• *= a *= b a = a*b
• /= a /= b a = a/b
• %= a %= b a = a%b
C Relational Operators
• A relational operator checks the relationship between two
operands. If the relation is true, it returns 1; if the relation is
false, it returns value 0.
• Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
• == Equal to 5 == 3 returns 0
• > Greater than 5 > 3 returns 1
• < Less than 5 < 3 returns 0
• != Not equal to 5 != 3 returns 1
• >= Greater than or equal to 5 >= 3 returns 1
• <= Less than or equal to 5 <= 3 return 0
• char: The most basic data type in C. It stores a
single character and requires a single byte of
memory in almost all compilers.
• int: As the name suggests, an int variable is used
to store an integer.
• float: It is used to store decimal numbers
(numbers with floating point value) with single
precision.
• double: It is used to store decimal numbers
(numbers with floating point value) with double
precision.
e is an integer between -16445 and 16320
Use of data
types and
extensions
INPUT AND OUTPUT OPERATIONS
What are file input output
operations?
• Input/Output
operations such
as open, close,
read, write and
append, all of
which deal with
standard disk or
tape files.
OPERATORS & EXPRESSIONS
9. Precedence of Operators
Increment and decrement
• C has two special unary operators called
increment ( ++ ) and decrement ( -- )
operators. These operators increment and
decrement value of a variable by 1 . ++x is
same as x = x + 1 or x += 1. --x is same as x = x -
1 or x -= 1. Increment and decrement
operators can be used only with variables.
ARRAYS
• It is a linear data structure that groups elements of
similar types and stores them continuous memory
location.
• Array subscript: Index Number.
• 1st element Index = 0
• Last element Index =
(Num of elements of array) – 1
Operations performed on arrays
1. Insertion.
2. Deletion.
3. Traversal.
4. Sorting.
5. Searching.
Merging, Copying, Reversing.
Array Initialization
• <data-type> <array_name>[size]={element 1,
element 2……. element n};
• Example: int A[3]={ 2, 6 , 9};
or
• <array_name>[index_number]=<element>;
• Example: A[0]=2;
Array Size( in bytes)
• Size of a single dimensional array:
array size= length * size of data type
Example:
int A[4]={10,20,30,40};
Size of A= 4*2=8 bytes
Array Representation
• Logical Representation of Single Dimensional
array.
MULTI DIMENSIONAL ARRAY
Array Declaration
• <data-type> <array_name>[row-subscript][col-
subscript] ;
• Example: int A[2][2];
Array Initilization
• <array_name>[row-index_number][column-
index_number] = <element>;
• Example: int A[1][0];
• <data-type><array_name> >[row-subscript][col-
subscript] ={element 1, element 2……. element
n};
• Example: int A[2][2]={1, 2, 6 , 9};
A[0][0]=1 A[0][1]=2 A[1][0]=6 A[1][1]=9
Array Size( in bytes)
• Size of a single dimensional array:
array size= row-size*column-size* size of data
type
Example:
int A[2][2]={10,20,30,40};
Size of A= 2*2*2=8 bytes
Array Representation
• Logical Representation of Multi Dimensional
array.
MULTI DIMENSIONAL ARRAY
Example:
STRINGS
• String is a sequence of characters
terminated with a null character \0
• Character array stores a group of characters
that collectively represent a string.
• Syntax: <data_type> <string name>[size] =
“string-characters”;
• Example: char str[10]=“hello”;
String Functions
// STRING LENGTH
#include <stdio.h>
#include <string.h>
int main( )
{
int len;
char array[20]= "hello.hi";
len = strlen(array) ;
printf ( "\string length = %d \n" , len ) ;
return 0;
}
// STRING REVERSE for(i=0;i<len;i++)
#include <stdio.h> revstr[len-i-1]=str[i];
#include <string.h> revstr[len]='\0';
void main() printf("Reverse of string
{ %s is: %s", str,revstr);
char str[30],revstr[30]; //getch();
int i,len; }
printf("Enter a string");
scanf("%s",&str);
//gets(str);
len=strlen(str);
// STRING CONCAT // concatenate s2 to s1
#include <stdio.h> for (j = 0; s2[j] != '\0'; ++j,
int main() { ++length) {
char s1[100] = "BNMIT ", s1[length] = s2[j];
s2[] = " Open elective "; }
int length, j; // terminating the s1 string
// store length of s1 in the s1[length] = '\0';
length variable printf("After concatenation:
length = 0; ");
while (s1[length] != '\0') { puts(s1);
++length; return 0;
} }
BUILT IN FUNCTIONS
• Any function that is provided as part of a high-
level language and can be executed by a
simple reference with specification of
arguments.
Structure in c
• A structure is a key word that create user
defined data type in C
• A structure creates a data type that can be
used to group items of possibly different types
into a single type.
• 'struct' keyword is used to create a structure.
Pointers
• It is a derived data type that stores memory
address as its value.
• It points to the location where another
variable is stored.
• Used for dynamic memory management.
• Declaration: * int num=10;
int *ptr; //Declaration
• Initialized: & ptr=# //Initialized
int a;
int *ptr; //ptr declaration
a=50;
ptr=&a; // ptr allocation
address of a= ?
value of a = ?
address of ptr= ?
value of ptr= ?
#include <stdio.h>
int main()
{
int a = 10;
int *p;
p = &a;
printf("p = %u\n", p);
printf("*p = %d\n", *p);
printf("&p = %u\n", &p);
printf("*&p = %u\n", *&p);
return 0;
a=*b+*c // Pointer expressions
z=z+*y;
*c=*ptr+5;