C PROGRAMMING
Books
The C Programming Language
Language, by Dennis Ritchie and Brain Kernighan
Balaguruswamy,
g y, Programming
g g in ANCI C”,, 2nd Edition
Herbert Schildt. “The Complete Reference C ”, 4th Edition
Compilers
Gcc compiler
Use any editor based on gcc compilers
- codeblocks
- dev C++
Or you can use any online compiler like
- codechef
-and others
Your First
C PROGRAM !!!!!
Simplest C Program
Hash
#include<stdio.h>
int main()
{
printf(“ Programming in C is Interesting
printf( Interesting”););
return 0;
}
Preprocessor Directive
# include: Is a preprocessor directive which directs to
include the designated file which contains the declaration
of library functions (pre defined).
stdio.h (standard input output) : A header file which
contains declaration for
f standard input and output
functions of the program.Like printf, scanf
When to use preprocessor directive
When one or more library functions are used, the
corresponding header file where the information about
these functions will be present are to be included.
When you want to make use of the functions(user-
defined) present in a different program in your new
program the source program of previous function has to
be included.
Defining main( )
When a C program is executed, system first calls
the main(( ) function,, thus a C p
program
g must
always contain the function main( ) somewhere.
A function definition has:
heading
{
declarations ;
statements;
}
Basic Structure of a C program
preprocessor directive
int main( )
{
declarations;
_________________;
______body_______;
body ;
_________________;
return 0;
}
Concept of Comment
Comments are inserted in program to maintain the clarity
and for future references.
references They help in easy debugging
debugging.
Comments are NOT compiled, they are just for the
programmer to maintain the readability of the source
code.
Comments are included as
/* ……………..
………………………………*/
*/
Check this out!
#include<stdio.h>
int main()
{
printf("
i tf(" IIndia
di won the
th fifinall cricket
i k t match
t h iin S
Srii
Lanka ");
return 0;
}
Notion of keywords
Keywords are certain reserved words, that have standard
predefined meanings in C.
All keywords are in lowercase.
Some keywords in C:
auto extern sizeof break
static case for struct
goto switch const if
typedef enum signed default
int union long continue
unsigned do register void
double return volatile else
short
h t while
hil fl t
float char
h
Identifiers and Variables
Identifier : A name has to be devised for program
elements such as variables or functions.
Variable:
Variables are memory regions you can use to hold data while
your program is running.
Thus variable has an unique address in memory region.
region
For your convenience, you give them names (instead of
h i tto kknow th
having the address)
dd )
Because different types of data are different sizes, the
computer needsd to kknow what
h type eachh variable
i bl iis – so iti
can reserve the memory you need
Rules for Identifiers
Contains
C t i only l letters,
l tt digits
di it and
d under
d score characters,
h t
example amount, hit_count
Must begin with either a letter of the alphabet or an underscore
character.
Can not be same as the keywords, example it can not be void,
int.
Uppercase letters are different than lowercase, example
amount Amount and AMOUNT all three are different
amount,
identifiers.
Maximum length g can be 31 characters.
Should not be the same as one already defined in the library,
example it can not be printf/scanf.
No
N speciali l characters
h t are permitted.
itt d e.g. blank
bl k space,period,
i d
semicolon, comma etc.
PRE DEFINED
DATA TYPES
Data Types
Every program specifies a set of operations to be done on
some data in a particular sequence.
However,, the data can be of manyy types
yp such as a
number, real, character, string etc.
C supports many data types out of which the basic types
are:
int, float , double and char.
Four Basic Data Types
In C, there are 4 basic data types:
1 char,
1. char
2. int,
3 Float and
3.
4. Double
Each one has its own properties.For instance,they all
have different sizes.
sizes
The size of a variable can be pictured as the number of
memory slots that are required to store it.
it
Integer types
Type Storage size Value range
char
h 1 byte
b t -128
128 to
t 127 or 0 to
t 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128
128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -
2,147,483,648 to 2,147,483,647
unsigned
i d int
i t 2 or 4 bytes
b t 0 to
t 65
65,535
535 or 0 tto
4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to
2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Float types
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte or 12 byte 3.4E-4932 to 19 decimal places
1.1E+4932
#include <stdio.h>
int main(void)
{
int integerType;
float floatType;
d bl ddoubleType;
double bl T
char charType;
long double a;
// Sizeof operator is used to evaluate the size of a variable
printf("Size of int: %ld bytes\n",sizeof(integerType));
printf("Size
printf( Size of float: %ld bytes\n
bytes\n",sizeof(floatType));
sizeof(floatType));
printf("Size of double: %ld bytes\n",sizeof(doubleType));
printf("Size of char: %ld byte\n",sizeof(charType));
printf("Size
i tf("Si off short:
h t %ld bbyte\n",sizeof(short));
t \ " i f( h t))
printf("Size of long: %ld byte\n",sizeof(long));
printf("Size of long double : %ld byte\n",sizeof(a));
return 0;
}
Format specifiers
There are several format specifiers-The one you use should
depend on the type
y of the variable yyou wish to print out.The
common ones are as follows:
Format Specifier Type
%d int
%c char
%f float
%lf double
%s string
To display a number in scientific notation,use %e.
To display a percentage sign,use %%
printf( )
1. It is used to print message or result on the output screen.It is define in
stdio.h header file.
2. Returns the number of characters it outputs on the screen.
Example:
printf( “Enter the number whose multiplication table you want to generate”);
printf( “ Balance in your account is %d”, bal); /* where bal is int type*/
printf(“Balance =%d,Total tax is %f ” ,bal, tax); /* where tax is float type */
scanf( )
scanf( ) : It is used to input from the user numerical values,
characters or strings.It
g is defined in stdio.h
The function returns the number of data items that have been
entered successfully.
Example:
int num1,num2,num3;
char var;
printf(“ enter the numbers “);
scanf(“%d%d%d”,
f( % % % &num1,&num2,&num3);
& & & )
printf(“enter a character”);
scanf(“%c”,
f(“% ” &var);
& )
scanf( )
Don’t
Don t try to display a decimal number using the integer format
specifier,%d, as this displays unexpected values.
Similarly,don’t use %f for displaying integers.
Mixing %d with char variables, or %c with int variables is all
right
scanf( )
This function returns the number of data items that have
been entered successfullyy
#include<stdio.h>
Similarly Write a program to
int main() find out what does printf( )
{ returns????
int n;
printf("enter
printf( enter the value
value");
);
printf("%d", scanf("%d",&n));
return 0;
}
Char Data type
A variable of type char can store a single character.
All character have a numeric code associated with
them, so in reality while storing a character variable its
numeric value gets stored.
The set of numeric code is called as “ASCII”,
ASCII ,
American Standard Code for Information Interchange.
Char takes 1 byte
ASCII codes
Declaration of Variable
To Declare a variable means to reserve memory space for it.
In the declaration variable is provided a name which is used
through out the program to refer to that character.
Example:
char c;
OR
char c, k, l;
D
Declaring
l i the
th character
h t does
d nott initialize
i iti li the
th variable
i bl with
ith the
th
desired value.
Memory view
char type
Each variable has an
unique address of i
memory location
associated with it
integer
Important about Variable
Always remember in C , a variable must always be declared
before it used.
Declaration must specify the data type of the value of the variable.
Name of the variable should match with its functionality /purpose.
Example int count ; for counting the iterations.
iterations
float per_centage ; for percentage of student
Char data type
Characters (char) – To store a character into a char
variable,you,y must enclose it with SINGLE Q QUOTE marks
i.e. by ‘ ’.
The double quotes are reserved for string(a collection of
character).
h )
The character that you assign are called as character
constants.
constants
You can assign a char variable an integer.i.e. its integer
value.
‘a’, ‘z’ , ‘A’ , ‘Z’ , ‘?’, ‘@’, ‘0’, ‘9’
- Special
p Characters: ppreceded byy \
‘\n’, ‘\t’ , ‘\0’, ‘\’’, ‘\\’ etc.
Initialization
Initializing a variable involves assigning(putting in) a value for
the first time.This is done by using the ASSIGNMENT
OPERATOR, denoted by the equals sign,=.
Declaration and initializing can be done on separate lines, or
on one liline.
char c=‘x’;
c= x ; or
char c;
c= x
c=‘x’
Printing value of char variable
printf( “%c”
%c , a);
This causes the “ %c” to be replaced by value of
character variable a.
printf(“\n %c”, a);
“\n” is a new line character which will print the value of
variable on newline.
newline
Variables and Constants
Variables are like containers in your computer’s
computer s memory-
you can store values in them and retrieve or modify them
when necessaryy
Constants are like variables,but
, once a value is stored,its
,
value can not be changed.
Naming Variables
Expressions
Expressions consist of a mixture of constants,variables
constants variables and
operators .They return values.
Examples are:
– 17
-X
X*B/C+A
B/C+A
– X+17
Program using character constants
#include<stdio.h>
#include<stdio h>
int main()
{
char a,b,c,d; /* declare char variables*/
char e='o'; /* declare char variable*/
a='H'; /* initialize the rest */
b='e'; /* b=e is incorrect */
c='l'; /* c=“l” is incorrect*/
d=108; /* the ASCII value of l is 108 */
printf("%c%c%c%c%c" a b c d e)
printf("%c%c%c%c%c",a,b,c,d,e);
return 0;
}
Integer Data Type
Variables of the int data type represent whole numbers.
If you try to assign a fraction to an int variable,the decimal
part is ignored and the value assigned is rounded down from
the actual value.
Also assigning a character constant to an int variable assigns
the ASCII value.
value
Program
#include<stdio.h>
main()
{ int a,b,c,d,e;
a=10;;
b=4.3; a=10
c=4.8;
d='A';
d A; b=4
e= 4.3 +4.8; c=4
printf("\n a=%d",a);
printf("\n
printf( \n b
b=%d"
%d ,b);
b); d=65
printf("\n c=%d",c); e=9
printf("\n d=%d",d);
printf("\n
printf( \n e=%d
e=%d",e);
e); b+c=8
printf(“\n b+c=%d”,b+c);
return 0;
}
Float data type
• For storing decimal numbers float data type is used.
used
• Floats are relatively easy to use but problems tend to occur
when performing division
In general:
An int divided by an int returns an int.
int
An int divided by a float returns a float.
A float divided by an int returns a float.
float
A float divided by a float returns a float.
int and float data types
Integers (int) -- %d
0 1 1000 -1 -10 666
Floating point numbers (float) -- %f
1.0 .1 1.0e-1 1e1
Program
#include<stdio.h>
#include<stdio h>
main( )
{
return 0; float a=3.0; a=3.000000
fl t b=
float b 4.00
4 00 + 77.00;
00 b=11 000000
b=11.000000
printf(“a=%f “,a);
printf(“\n
i tf(“\ b=%f
b %f ““,b);
b)
}
int and float
Float is “ communicable type “
Example:
1 + 2 * 3 - 4.0
4 0 / 5
= 1 + (2 * 3) - (4.0 / 5)
= 1 + 6 - 0.8
= 6.2
Example 2
(1 + 2) * (3 - 4) / 5
= ((1 + 2) * (3 - 4)) / 5
= (3 * -1) / 5
= -3
3 / 5
= 0
Multiple Format specifiers
• You could
Y ld use as many fformatt specifiers
ifi as you wantt
with printf-just as long as you pass the correct number of
a gu e ts
arguments.
• The ordering of the arguments matters.The first one
should corresponding to the first format specifier in the
string and so on. Take this example:
printf( “a=%d,b=%d, c=%d\n”, a , b, c);
If a,b
b andd c were iintegers,this
t thi statement
t t t will
ill print
i t th
the
values in the correct order.
• Rewriting the statement as
printf( “a=%d,b=%d, c=%d\n”, c,a,b);
Would still cause the program to compile OK,but
OK but the values
of a,b and c would be displayed in the wrong order.
Statements
Statements
Which of these are valid:
int = 314.562 * 50; Not valid
3.14 * r * r = area; Not valid
k = a * b + c(2.5a + b); Not valid
m_inst = rate of int * amt in rs; Not valid
km = 4; valid
area = 3.14 * r * r;; valid
S.I. = 400; Not valid
sigma-3
sigma 3 = d; Not valid
Statement Blocks
Types of Constants
OVERVIEW OF C
The C language
General ppurpose
p and Structure pprogramming
g g language.
g g
Rich in library functions and allow user to create additional library
functions which can be added to existing ones.
Highly portable: Most C programs can run on many different machines
with almost no alterations.
It gives user the flexibility to create the functions, which give C immense
power and scope.
C – Middle Level Language
It combines both the powerful and best elements of high level
languages as well as flexibility of assembly language.
C resembles high level language such as PASCAL,
FORTRAN as it contains keywords like if, else, for and while.
It also uses control loops.
C also possesses the low level features like pointers, memory
allocation and bit manipulation
p
C – Structured Language
C supports the breaking down of one big modules into smaller
modules.
It allows you to place statements anywhere on a line and does
not require a strict field concept as in case of FORTARN or
COBOL.
COBOL
It consist of functions which are building blocks of any
program. They give the flexibility of separating tasks in a
pprogram
g and thus ggive modular pprogramming
g g approach.
pp
Size of data types
Size of data types is compiler and processor types
dependent.
yp can be determined byy usingg sizeof
The size of data type
keyword specified in between parenthesis
For Turbo 3.0 compiler, usually in bytes
– char -> 1 bytes
– int
i t -> 2 bbytes
t
– float -> 4 bytes
– double
d bl ->> 8 bytes
b t
Output??
#include <stdio.h>
int main(void)
{ int a=72; a equals 72
char b=
b='A';
A; a equals H
printf("a equals %d \n",a); b equals 65
printf("aa equals %c \n
printf( \n",a);
a); b equals A
printf("b equals %d \n",b);
printf("bb equals %c \n
printf( \n",b);
b);
return 0;
}
Example
printf(“%d”,9876) 9 8 7 6
printf(“%6d”,9876) 9 8 7 6
printf(
printf(“%2d”
%2d ,9876)
9876) 9 8 7 6
printf(
printf(“%-6d”,9876)
% 6d ,9876) 9 8 7 6
printf(“%06d”,9876) 0 0 9 8 7 6
Example
printf(“%7.4f”,98.7654) 9 8 . 7 6 5 4
printf(“%7.2f”,98.7654) 9 8 . 7 7
printf(“%-7.2f”,98.7654) 9 8 . 7 7
printf(“%f”,98.7654) 9 8 . 7 6 5 4 0 0
Note:-Using precision in a conversion specification in the
format control string of a scanf statement is wrong.
Formatting Strings
•The
The printf(
printf(“:%s:\n”,
:%s:\n , “Hello,
Hello, world!
world!”);); statement prints the string
(nothing special happens.)
•The printf(“:%15s:\n”, “Hello, world!”); statement prints the string, but
print 15 characters. If the string is smaller the “empty” positions will be
filled with “whitespace.”
•The
Th printf(“:%.10s:\n”,
i tf(“ % 10 \ ” “Hello,
“H ll world!”);
ld!”) statement
t t t prints
i t the
th string,
ti
but print only 10 characters of the string.
•The printf(“:%-10s:\n”, “Hello, world!”); statement prints the string,
but prints at least 10 characters. If the string is smaller “whitespace” is
added at the end.
•The printf(“:%-15s:\n”, “Hello, world!”); statement prints the string,
but prints at least 15 characters. The string in this case is shorter than
the defined 15 character, thus “whitespace” is added at the end (defined
by the minus sign.)
•The printf(
printf(“:%
:%.15s:\n
15s:\n”, “Hello
Hello, world!
world!”);); statement prints the string,
string
but print only 15 characters of the string. In this case the string is
shorter than 15, thus the whole string is printed.
•The printf(“:%15.10s:\n”, “Hello, world!”); statement prints the string,
but print 15 characters.
If the string is smaller the “empty” positions will be filled with
“whitespace.” But it will only print a maximum of 10 characters, thus
only part of new string (old string plus the whitespace positions) is
printed.
•The
The printf(
printf(“:%-15.10s:\n”,
:% 15.10s:\n , “Hello,
Hello, world!
world!”);); statement prints the
string, but it does the exact same thing as the previous statement, accept
the “whitespace” is added at the end.
Example
#include<stdio.h>
main()
{
pprintf(":%s:\n",
( % , "Hello,, world!");
);
printf(":%15s:\n", "Hello, world!");
printf(":%.10s:\n", "Computer");
printf(":%-10s:\n",
printf( :% 10s:\n , "Computer");
Computer );
printf(":%-15s:\n", "Computer");
printf(":%.15s:\n", "Computer");
printf(":%15.10s:\n",
printf( :%15.10s:\n , "Computer");
Computer );
printf(":%15.10s:\n", "Computer Science");
printf(":%-15.10s:\n", "Computer");
printf(":%-15.10s:\n",
printf( :% 15.10s:\n , "Computer
Computer Science
Science"););
}
Backslash ( \ ) character constants
\n : To include new line
\b : backspace
\r : carriage return
\t : horizontal tab
\a : alert
\” : double quote
\’ : single quote
\ : vertical
\v ti l tab
t b
\ \ : backslash
Exercise
Write a C program to compute the percentage of a
student in five subjects.
Input the marks in five subjects from the user.
user
Maximum marks in all the subjects is 100.