C Demo
C Demo
C Demo
C -Programming
By
Prof Imran Qureshi
(Computer Science)
2
Language : Media of communication
• Natural Language
Paragraph
Alphabets Words Sentences Pages
s
• Programming Language
Alphabets/ C-
C-Words/ C C
Digits/Sp. Statements/
Tokens Functions Programs
char Instructions
3
General Structure of C Programs
Documentation Section
Link Section or Header Section
Definition Section
Global Declaration Section
main( ) Function Section
{
Variable declaration/Initialization;
Program statements;
}
Subprogram Section
function1( )
.
.
functionn( )
4
#include<string.h>
strcat(s1,s2) Concatenates string s1to the end of s1.
strcmp(s1,s2) Compares strings s1 and s2.
strcpy(s1,s2) Copies the string s2 to s1.
#include<ctype.h>
tolower(x) Returns lower case equivalent of character x
toupper(x) Returns upper case equivalent of character x
#include<stdio.h>
printf( ) Writes arguments to stdout in specified format.
scanf( ) Reads arguments from stdin in specified format.
fopen( ) Opens the identified file.
fclose( ) Closes the identified file.
#include<math.h>
sin(x) Sine of x, x in radians
cos(x) Cosine of x, x in radians
exp(x) Exponential function ex
log(x) Natural logarithm ln(x), x>0
pow(x,y) xy
ceil(x) Smallest integer grater than x.
floor(x) Largest integerProf
smaller than x.
Imran Qureshi 5
First C Program
#include<stdio.h>
void main()
{
printf(“Hi! This is our First Program”);
}
• Type above code and save it as first.c
using text editor and compile it using..
– gcc first.c
– Execute it using…
– ./a.out
6
C Character Set
Letters Digits
Uppercase A……Z Decimal digits 0…..9
Lowercase a…….z
Special Characters White Spaces
! * + \ “ Blank space
< # ( = |
Horizontal tab
{ > % ) ~
; } / ^ - Carriage return
[ : , ? &
_ ] . ‘ New line
Form feed
7
C Words or tokens
enum signed
9
Identifiers
• Identifiers are used for naming variables,
functions and arrays.
• Identifiers follow the below listed rules :
– Alphabets, digits, underscores and dollar signs are
permitted.
– They must not begin with a digit.
– First character must be a letter or an underscore.
– Uppercase and lower case letters are distinct.
– They can be of any length however the first 8
characters are treated as significant by the C
compiler.
– Special Characters are not allowed
– Keywords, cannot be used as identifier.
10
Variables
• A variable is an identifier that is used to store a data
value.
• It is a symbolic name assigned to the memory location
where data is stored.🡺 Range depends on size of
memory location
• A variable can have only single data item/value at any
given time during the program execution.
• A variable can take different values at different times
during execution.
• Which values are stored in variable depends on Data
Types
• For assigning a value to a variable, we use
assignment operator (=).
3 X
11
Constants And Literals
• Constants are the identifier that represent fixed
values. This Value is not to be altered during
execution They are called as a symbolic
constant and they are associated with literals
• Literals means values or data items which can
be directly used within the programs
• There are total 2 types of the constant or literal
– String Constant
• Character Constant
• String Constant
– Numeric Constant
• Integer Constant
• Floating Point Constant
12
String Constants
• Character Constants
– It is a single character, enclosed in apostrophes (single quotation
marks).
– All the character constants has their own unique ASCII values
• String Constant
– It contains sequence of characters enclosed in double quotation
marks.
13
•
Numeric
Integer Constant
Constants
– It’s an integer valued number.
– It consists a sequence of digits.
– Types of Integer Constants as follows;
14
Special Symbols
Name Uses
parenthesis ( ) Used for defining precedence in expressions.
Used for surrounding cast types.
braces { } Used to initialize the arrays.
Used to define a block of code.
brackets [ ] Used to declare array types.
semicolon ; Used to separate statements.
comma , Usedtoseparateidentifiers in a variable
declaration.
Used inside a ‘for’ statement.
-> pointer to structure member reference.
dot . Structure member reference.
ampersand & Is called as address of operator.
Used to assign addressof the location of a
variable.
Used in the scanf function.
asterisk * Pointer reference(indirection).
15
Data Types
16
Fundamental Data Types
Datatyp Description Memory
e Requirement
17
Type Size(in bytes) Range
char 1 –128 to 127
int 2/4 –32,768 to 32,767
unsigned char 1 0 to 255
signed char 1 –128 to 127
unsigned int 2 0 to 65535
signed int 2 –32,768 to 32,767
short int 2 –32,768 to 32,767
unsigned short int 2 0 to 65535
signed short int 2 –32,768 to 32,767
long int 4 –2147483648 to 2147483647
signed long int 4 –2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+38
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932
bool 1(bit) 0 to 1
18
User-defined Data Types
19
The enum Data Type
• The enum Data Type
– An enumeration is a list of constant values.
– It is used to declare variables that can have
one of the values enclosed within the braces.
These values are also called as enumeration
constants.
• Example
enum color {green, blue, red, pink}; //green, blue, red, pink are constants
// or values
enum color flowers, leaves; //flowers and leaves are variables
flowers = red;
leaves = green;
20
Operators
Operators
Unary Relational
Operator Operator
(-,++,--) (<,>,<=,>=.
.)
21
Expressions
• An expression is a combination of
variables, constants and operators
arranged as per the syntax of the language.
Algebraic expression C expression
ab – c (a * b) – c
ab/c a*b/c
(m + n)(x – y) (m + n) * (x – y)
4x2 + x (4 * x * x) + x
22
Operators Precedence and Associativity
Operators Category Operators Associativity Level
23
Automatic Type Conversion
• It is also possible to store value of one type into a variable of
another type without a cast i.e. automatic conversion.
• It is possible only if the destination type has enough memory space
to store the source value.
• When operands in an expression are of different data types, the
lower type is converted in to the higher type before the operation
proceeds.
• If one operand is floating point and other is integer, the integer is
converted in to floating point and the result is floating point.
• If one of the operands is long double, convert the other to long
double and result is long double.
• And in the final, the result of the expression is converted in to the
type of the variable on the left of the ‘=’ sign and in this process the
following changes may occur:
– float to int causes truncation of the fractional part to zero.
– double to float causes rounding of digits.
24
Type Casting
• Type casting forcefully converts the value
of one type into another type.
• Syntax : (type) expression;
• Example :
– x =(int)10.456; //10.456 converts to 10.
– int a = 34; z = (float) a; // 34 converts to
34.000000
– y = (int)a + b; // Result of a+b is
converted to integer
25
Formatted Input and Output
• The scanf() function :This function is used to accept formatted
data from the keyboard , where format of string is depends on the
control string.
• Syntax :
• int scanf(“control string”,&var1,&var2,&var3…&varn);
• Where &var1,&var2…&var3 are the parameters of functions that
means variable names, showing the addresses of memory
location where data is to be stores.
• The control string consist of
• 1. White space characters (space,\t,\n,\v,\r,\f)
• 2. Conversion characters (d,c,i%.,o,u,s,e,f,g,x,[..])
• 3. A printable characters which specifies delimiter in between
two data items.
• 4. Modifier which tells size and type of the data item.
• Syntax :
• %[modifier]conversion_character
26
The scanf statement
Modifier Conversion Characters
1. Control Statement :
The control statements are used to control the flow of the program.
This is done by testing the conditions and then taking decisions
that which statements to be executed and which not to be.
37
Flow Control Structures
38
The goto Statement
• The goto statement changes the normal
sequence of a the program execution by
transferring control to other part of the
program.
• The goto statement is usually not used
because C is completely structured
language and most probably, the break
and continue statements are used.
• goto aa;
39
Simple if Statement
• It is a two-way decision statement. Depending
on whether the value of expression is ‘true’ or
‘false’, it transfers the control to a particular
statement.
• Syntax
• if (test expression)
• {
• True-block statements;
• }
• statement-x;
40
The If…else Statement
• This statement allows selecting one of the two available options
depending upon the output of the test expression
if (test expression)
{
True-block statements;
}
else
{
False-block statements;
}
statement-x
41
/* program to accept an integer & check it
is even or odd */
/* Exerise 2 set A Assignment no:1 */
#include<stdio.h>
main()
{
int a;
printf("Enter a no:");
scanf("%d",&a);
if(a%2==0)
printf("The No is even\n");
else
printf("The N0 is odd\n");
}
/*output
[fy125145@localhost setA]$ cc odd.c
[fy125145@localhost setA]$ ./a.out
Enter a no:15
The N0 is odd
[fy125145@localhost setA]$ ./a.out
Enter a no:16
The No is even
*/
Prof Imran Qureshi 42
/* program to accept an character & check
wheather it is a digit*/
/* Exerise 2 set A Assignment no:3 */
#include<stdio.h>
main()
{
char ch;
printf("Enter the Charecter:");
scanf("%c",&ch);
if(ch>'0' && ch<'9')
printf("%c is a digit\n",ch);
else
printf("%c is a not digit\n",ch);
}
/*output
[fy125145@localhost setA]$ cc digit.c
[fy125145@localhost setA]$ ./a.out
Enter the Charecter:d
d is a not digit
[fy125145@localhost setA]$ ./a.out
Enter the Charecter:6
6 is a digit
*/
Prof Imran Qureshi 43
/* program to accept an integer & check it
is div by 5 & 7 */
/* Exerise 2 set A Assignment no:4 */
#include<stdio.h>
main()
{
int a;
printf("Enter a no:");
scanf("%d",&a);
if(a%5==0 && a%7==0)
printf("%d is divisible by 5 & 7\n",a);
else
printf("%d is not divisible by 5 & 7\n",a);
}
/*output
[fy125145@localhost setA]$ cc div.c
[fy125145@localhost setA]$ ./a.out
Enter a no:35
35 is divisible by 5 & 7
[fy125145@localhost setA]$ ./a.out
Enter a no:45
45 is not divisible by 5 & 7
*/
Prof Imran Qureshi 44
a leap year or not
Exerise 2 set B Assignment no:3 */
#include<stdio.h>
main()
{
int a;
printf("enter any year:");
scanf("%d",&a);
if ((a%4==0 && a%100!=0)|| a%400==0)
printf("%d is leap year\n",a);
else
printf("%d is not leap year\n",a);
}
/*output
[fy125145@localhost setB]$ cc leap.c
[fy125145@localhost setB]$ ./a.out
enter any year:1900
1900 is not leap year[fy125145@localhost
setB]$ cc leap.c
[fy125145@localhost setB]$ ./a.out
enter any year:1984
1984 is leap year
[fy125145@localhost setB]$ ./a.out
enter any year:1999
1999 is not leapProf
year
Imran Qureshi 45
The nesting of If…else Statements
if (test expression1)
{
if (test expression2)
{
statement -1;
}
else
{
statement – 2;
}
Fig. 5.7
}
else
{
statement - 3;
}
statement – x;
46
The else If Ladder
• if (condition - 1)
• statement – 1;
• else if (condition - 2)
• statement – 2;
• else if (condition - 3)
• statement – 3;
• …………………………….
• else if (condition - n)
• statement – n;
• else
• default – statement;
47
The switch Statement
• We use if statements to choose one of the many alternatives. But as the
number of alternatives increases, the complexity of such a program also
increases. Thus, to make it simpler, C has a multi-way decision statement
known as switch.
• A case expression can be repeatedly used in a switch statement. That is it
allows several alternate courses of actions and choose one to be executed at
runtime.
• The use of break statement in every case is used to quit the switch statement
after a particular case is matched. Thus only one case gets executed. If the
break statement is not used, then all the statements following the matched
case will get executed. Thus break statement is compulsory for the proper
execution of the switch statement.
switch (expression)
{
case value – 1: // value -1 is a constant and is known as case label.
Statement1;
break; // end of case
case value – 2: // case labels end with a colon (:).
Statement1;
break;
default: //optional
default – Statement;
break;
}
statement – x;
48
/* Write a program, which accepts two
integers and an operator as a character (+
- * /), performs the
corresponding operation and displays the
result
Exerise 3 set A Assignment no:2 */
#include<stdio.h>
main()
{
int n1,n2,a,m,d1,s,d2;
char ch;
printf("Enter two integers & operator:");
scanf("%d %d %c",&n1,&n2,&ch);
a=n1+n2;
m=n1*n2;
d1=(float)n1/n2;
d2=(float)n2/n1;
s=n1-n2;
56
#include<stdio.h>
main()
{
int x=1;
do
{
printf("%d\t",x);
x++;
}while(x<=10);
}
58
/*program to accept a no & check it is
Fibnacci no or not
Exerise 4 set B Assignment no:1*/
#include<stdio.h>
main()
{
int n,n1=0,n2=1,i=1,n3;
printf("Enter a no:");
scanf("%d",&n);
while(i<=n)
{
n3=n1+n2;
printf("The no's are %d\n“,n3);
n1=n2;
n2=n3;
i++;
}
}
62
Nested loop s
• Rules of the nested loop
1) Inner loop and outer loop should not overlap with each
other.
2) Running variables used in the loops are to be
independent or separate.
3) Direct jump from inner loop to outer loop is allowed but
jump from outer loop to inner loop is not allowed.
4) We can use for loop within while loop or do-while loop
and vice vrsa.
5) If total iteration of outer loop is n (i.e. body of loop of
outer loop is executed n times) and iteration of inner loop
is m then body of inner loop is executed m*n times. This
m may vary according to condition.
63
#include<stdio.h>
main()
{
char ch='A';
int n,i=0,j;
printf("Enter lines you want:");
scanf("%d",&n);
for(i=n;i>=0;i--)
{printf("\n");
for(j=1;j<=i;j++)
printf("%c\t",ch++);
}
}
/*output
[fy125145@localhost setA]$ cc lines.c
[fy125145@localhost setA]$ ./a.out
Enter lines you want:6
A B C D E F
G H I J K
L M N O
P Q R
S T
U
Prof Imran Qureshi 64
*/
The break Statement
• The break statement is used to jump out of
a loop.
• An early exit from a loop can be
accomplished using the break statement.
When a break statement is encountered
inside a loop, the loop is immediately
exited and the program continues with the
statement immediately following the loop.
65
The continue Statement
• Sometimes, in the loop iterations, it may
be necessary to skip some statements in
that loop and start the next iteration of that
same loop. For such situations, C provides
continue statement.
• The continue statement causes the loop
to continue with the next iteration skipping
the remaining statements in that loop.
66
Functions
Functions
• A function is a named, self-contained block of statements
that perform a specific, well defined task and may return a
value to the calling program.
return;
return;
return expression; return b;
return(expression);
return(a+b);
• You can also assign the address of any function to a pointer by just
specifying the function_name without parenthesis.
• Example :
int fact(int n) // function to find the factorial of a given no.
{
……..
……..
}
main( )
{
int *pi(int); //pointer to function with prototype of fact
int x = 5; // number whose factorial is required
pi = fact; //assigning address of function fact to pointer pi
pi(x); //call to the function fact using pi
}
but some people can pack more into them than others
Please Note..
• Int x=5
• X variable
• 5 value
• 1002 address
• The variable x is associated with the memory address 1002. Since
memory addresses are just numbers, they can also be assigned to
any variables that can be stored in the memory location, like other
simple variables. Such variables that contain the memory address
are called Pointers.
• Thus, pointer is a variable that contains the address which is a
location of another variable in the memory.
• Suppose, we assign the address of x to variable p, then p is called
the pointer as it points to the variable x. This link between x and p is
shown below:
pointers
/*program to handle pointers*/
/*Remember that compiler only allocates memory to pointers
to store location, for data member it is require to use malloc finction*/
#include<stdio.h>
void main()
{ int *l,*b,*p;
l=(int*)malloc(sizeof(int));
b=(int*)malloc(sizeof(int));
p=(int*)malloc(sizeof(int));
printf("\nEnter Length");scanf("%d",l);
printf("\nEnter Breadth");scanf("%d",b);
*p=2*(*l + *b);
printf("\nLength = %d",*l);
printf("\nBreadth = %d",*b);
printf("\nPerimeter of Rectangle = %d",*p);
}
strlen(s1) Returns the length of the string s1 excluding the null character.
strcmp(s1, s2) Compares s1 and s2 and returns -ve if s1<s2, +ve if s1>s2, 0 if
s1=s2.
strcpy(s1, s2) Copies the string s2 into string s1, modifying the string s1.
strcmpi(s1, s2) Compares s1 and s2 ignoring the case and returns similar result
as strcmp
strncmp(s1, s2, n) Compares the first n characters of string s1 and s2 and returns
similar result as strcmp.
A r p i t a \0
S h a r a d a \
0
S I B A R M C A \
0
M A N I S H \0
N e e l i m a \0
A v a n t i k a \0
but some special people can pack more into them than others
By using this method structure date By using this method any function not
acts as global declaration and it is directly access structure date.
involved by all functions.
All members in the Union share the Each member in the Structure is
same storage area in the computer’s assigned its own unique storage area.
Example: Assume struct
Union SS{
UU{int
inta;a;
memory . float b; char c; } then sizeof SS would
UU(Union)
be >7 bytes would be 4dependendent-if
(compiler bytes.
Allocates the memory equal
int,float, char to as
are taken the
2,4,1) Allocates the memory equal to total
maximum memory required by the memory (sum of the memory)required
member. by all the members.
Only one member can be active at a All members can be active at a time.
time.
Only the first member of a union All members of a structure variable can
variable can be initialized. be initialized.
but some special people can pack more into them than others
Please Note..
Example :
FILE *fp;
if ((fp = fopen("myfile", "r")) = =NULL)
{
printf("Error opening file\n");
exit(1);
}
To close a file and disassociate it with a stream, use fclose().
Syntax : fclose(FILE *fp);
The fclose() function closes the file associated with fp, (which must be a valid file pointer previously
obtained using fopen()) and disassociates the stream from the file. The fclose() function returns 0 if
successful and EOF (end of file) if an error occurs.
The fcloseall() closes all the files opened previously.
Example :
FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen (filename,"w");
…….
……….
fclose (fptr);