0% found this document useful (0 votes)
12 views

C Module 1 Full

Uploaded by

Lakshmi priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C Module 1 Full

Uploaded by

Lakshmi priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

C Language

PRESENTED BY
Dr.Surendran.R
Professor CSE
Dept.,
CIT
Overview of C

 C is developed by Dennis Ritchie


 C is a structured programming language
 C supports functions that enables easy
maintainability of code, by breaking large file
into smaller modules
 Comments in C provides easy readability
 C is a powerful language
Contents
DATA TYPES  CODING
VARIABLES STANDARDS
TYPE DEF  FUNCTIONS
OPERATORS  ARRAYS
STATEMENTS  STRUCTURES
INPUT AND  UNIONS
OUTPUT  POINTERS
SAMPLE PROGRAM  ENUMERATIONS

GRAPHICS
Data types in C

 Primitive data types


 int, float, double, char
 Secondary data types
 Arrays come under this category
 Arrays can contain collection of int or float or
char or double data
 Structures and enum fall under this category.
Variables

Variables are data that will keep on changing


Declaration
<<Data type>> <<variable name>>;
int a;
Definition
<<varname>>=<<value>>;
a=10;
Usage
<<varname>>
a=a+1; //increments the value of a by 1
Demo 1
#include<stdio.h>
#include<stdio.h> int main()
int main() {
{ int a,b;
int a=10,b=12; scanf("%d
printf("%d",a+b); %d",&a,&b);
} printf("%d",a+b);
#include<stdio.h>}
int main()
{
int a=10,b=12,c;
C=a+b;
printf("%d",c);
}
Variable names- Rules

 Should not be a reserved word like int etc..


 Should start with a letter or an underscore(_)
 Example int a , int maths_marks
 Can contain letters, numbers or underscore.
 Example char my_123
 No other special characters are allowed
including space
 Example !,$,%,#
 Variable names are case sensitive
 A and a are different.
Type def

 The typedef operator is used for creating


alias of a data type
 For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
Operators

 Arithmetic (+,-,*,/,%)
 Relational (<,>,<=,>=,==,!=)
 Logical (&&,||,!)
 Bitwise (&,|)
 Assignment (=)
 Compound assignment(+=,*=,-=,/=,
%=,&=,|=)
 Shift (right shift >>, left shift <<)
Comments in C

 Single line comment


 // (double slash)
 Termination of comment is by pressing enter
key
 Multi line comment
/*….
…….*/
This can span over to multiple lines
Input and Output

 Input
 scanf(“%d”,&a);
 Gets an integer value from the user and stores
it under the name “a”
 Output
 printf(“%d”,a)
 Prints the value present in variable a on the
screen
For loops
The syntax of for loop is
for(initialisation;condition checking;increment)
{
set of statements
}
Eg: Program to print Hello 10 times
#include<stdio.h>
int main()
{
int I;
for(I=0;I<10;I++)
{
printf("\nHello");
}
return 0;
}
Go to
 The goto statement is a jump statement which jumps
from one point to another point within a function.
#include <stdio.h>
int main()
{
int n = 0;
loop:
{
printf("\n%d", n);
n++;
}
if (n<10)
goto loop;
return 0;
While loop
The syntax for while loop
while(condn)
{
statements;
}
Eg:
#include <stdio.h>
int main()
{
int a=10;
while(a != 0)
{ printf("\n%d",a);
a--;
}
return 0;
}
Do While loop
The syntax of do while loop
do
{
set of statements
}while(condn);
Eg:
#include <stdio.h>
int main()
{
int i=10;
do
{
printf("%d\n",i);
i--;
}while(i!=0);
return 0; }
Conditional statements

if (condition)
{
stmt 1; //Executes if Condition is true
}
else
{
stmt 2; //Executes if condition is false
}
Conditional statement

switch(var)
{
case 1: //if var=1 this case executes
stmt;
break;
case 2: //if var=2 this case executes
stmt;
break;
default: //if var is something else this will execute
stmt;
}
Input and Output

 Input
 scanf(“%d”,&a);
 Gets an integer value from the user and stores
it under the name “a”
 Output
 printf(“%d”,a)
 Prints the value present in variable a on the
screen
Header files

 The files that are specified in the include


section is called as header file
 These are precompiled files that has some
functions defined in them
 We can call those functions in our program
by supplying parameters
 Header file is given an extension .h
 C Source file is given an extension .c
Main function

 This is the entry point of a program


 When a file is executed, the start point is the
main function
 From main function the flow goes as per the
programmers choice.
 There may or may not be other functions
written by user in a program
 Main function is compulsory for any c
program
Running a C Program

Type a program
Save it
Compile the program – This will
generate an exe file (executable)
Run the program (.exe will create)
Program structure

A sample C Program

#include<stdio.h>
int main()
{
--other statements
}
Writing the first program

#include<stdio.h>
int main()
{
printf(“Hello”);
return 0;
}

This program prints Hello on the screen when


we execute it
Functions and Parameters

Syntax of function
Declaration section
<<Returntype>> funname(parameter list);
Function Call
Funname(parameter);
Definition section
<<Returntype>> funname(parameter list)
{
body of the function
}
Example function

#include<stdio.h>
void fun(int a); //declaration
int main()
{
fun(10); //Call
}
void fun(int x) //definition
{
printf(“%d”,x);
}
C Questions
1."\r" represents _______________
Choose one answer.
A. Back Space
B. Carriage return
C. Alert
D. Form Feed
Ans: B.
2. Which of the following cannot be checked in a switch case sta
Choose one answer.
A. Float
B. Integer
C. Character
D. Enum
Ans: A
3. Which of the following correctly shows the hierarchy of arithmetic operations in
C?
Choose one answer.
A. / + * -
B. * - / +
C. * / + -
D. + - / *
Ans: C
4. Print b to z using putchar
#include<stdio.h>
#include<conio.h>
void main()
{
char c = 'a';
while(c++ <= 'z') putchar(c);
getch();
}
5. In a function two return statements should never occur successively.
Choose one answer.
A. True
B. False
Constants
 A constant is an entity whose value can’t be changed
during the execution of a program.
Constants are classified as:
1. Literal constant
2. Qualified constants
3. Symbolic constants

1. Literal constant
integer constants,
floating-point constants,
character constants,

Integer constant
constant
Decimal 0..9
Octal 0…7
Hexa Decimal 1,2,3,……9, A,B,C,D,E,F
E.g.
Marks=90;

floating-point constant
Sequence of numeric digits with presence of decimal
points
E.g.
character constant
Only single character enclosed in single quote
E.g.
‘s’,’M’,’3’

String constants
Sequence of characters enclosed in double quotes
E.g.
“hai”
“2345”
Specifications of different
constants
Special constants
Sample program with \n \t

#include<stdio.h>
int main()
{
printf("This \a sentence will \t be printed \n in \t\t multi-
line \n\n bye");
return 0;
}
2. Qualified constants:
Qualified constants are created by using const qualifier.
E.g. const char a = ‘A’
The usage of const qualifier places a lock on the variable
after placing the value in it. So we can’t change the value
of the variable a

3. Symbolic constants
Symbolic constants are created with the help of the define
pre-processor directive.
For ex #define PI 3.14 defines PI as a symbolic constant
with the value 3.14.
VARIABLES

A variable is an entity whose value can change during the


execution of a program.
A variable is the name given to the memory location.
Eg:
1) Average
2) Height
Rules for defining variables
They must begin with a letter or underscore.
The variable name should not be a C keyword.
The variable names may be a combination of upper and lower
characters.
White space and special characters are not allowed.
Declaration of Variables
The syntax of declaring a variable is as follows:

Data_type variable_name;

Example:
int age;
char m;
int a, b, c;

Initializing Variables
Variables declared can be assigned or initialized using an assignment
operator ‘=’.
The declaration and initialization can also be done in the same line.
Syntax: variable_name = constant
or
data_type variable_name = constant
DATA TYPES

In C language data types are broadly classified as:


1. Basic data types (Primitive data types)
2. Derived data types
3. User-Defined data types
1. Basic data types:
There are five basic data types:
(i)Character - char
(ii)Integer - int
(iii) floating point - float
(iv)Double floating point - double
(v)No value available - void
2. Derived data types
These data types are derived from the basic data types.
Array
Pointer
Function

3. User-defined data types


The C language provides the flexibility to the user to create new
data types. These newly created data types are called user-
defined data types.
Structure
Union
Enumeration
Expressions Using
Operators in “C”
An expression is a sequence of operators and operands that
specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2
operators = & +

Operands
An operand specifies an entity on which an operation is to be
performed. It can be a variable name, a constant, a function call.
E.g: x=y%z Here x, y , z are operands

Operator
An operator is a symbol that is used to perform specific
mathematical or logical manipulations.
For e.g, x=y%z Here = , % are the operators
Question:
Find the operators and operands on following
i++
--j
K=x*b/z

Ans:
1. operators: ++ operands I
2. operators: -- operands j
3. operators: =,*,/ operands k,x,b,z
Simple Expressions & Compound Expressions
An expression that has only one operator is known as a
simple expression.
E.g: a+2
An expression that involves more than one operator is called a
compound expression.
E.g: b=2+3*5

Precedence of operators
The precedence rule is used to determine the order of
application of operators in evaluating sub expressions.
Each operator in C has a precedence associated with it.
The operator with the highest precedence is operated first.
Associativity of
operators
 The associativity rule is applied when two or more
operators are having same precedence in the sub
expression.
 An operator can be left-to-right associative or right-to-
left associative.
Category Operators Associativity Precedence

Level-1
Unary +, -, !, ~, ++, - -, &, sizeof Right to left
Level-2
Multiplicative *, /, % Left to right
Level-3
Additive +, - Left to right
Level-4
Shift << , >> Left to right
Level-5
Relational <, <=, >, >= Left to right
Rules for evaluation of expression

• First parenthesized sub expressions are evaluated first.


•((a+b)*c) If parentheses are nested, the evaluation
begins with the innermost sub expression.
• The precedence rule is applied to determine the order
of application of operators in evaluating sub expressions.
• The associability rule is applied when two or more
operators are having same precedence in the sub
expression.
Query 1:
What will be the output of the following arithmetic
expression?
5+3*2%10-8*6
a) 37 b) -37 c)47 d)-47

ANS: b
Query 2
#include<stdio.h>
int main()
{
int a=12,b=11,c=19,x,y;
x = a-3%2+c*2/4%2+b/4;
y = a = b+5-b+9/3;
printf("x=%d, y=%d\n",x,y);
return 0;
}
a)x=12,y=11 b)x=14, y=8 c)x=18,y=21 d)x=19,y=26

ans: b
*,/,%
x=12-3%2+19*2/4%2+11/4;
12-3%2+38/4%2+11/4 Y=11+5-11+3=8
12-3%2+9%2+2
12-1+38/4+2
12-1+1+2
14
Query 3

What will be output of following c program?


#include<stdio.h>
int main()
{
int a=-6;
a = -a-a+!a;
printf("%d\n",a);
return 0;
}

a)6 b)9 c)12 d)error

ans: c
Query 4

#include<stdio.h>
int main(void)
{
int a=14,b,c;
a=a%5;
b=a/3;
c=a/5%3;
printf("a=%d, b=%d, c=%d\n",a,b,c);
return 0;
}
a=14%5=4;
b=4/3=1;(a=4)
c=4/5%3=0
0%3=0

5%13 5
Classification of
Operators
 Classification based on Number of Operands
 Unary Operator: A unary operator operates on only
one operand. Some of the unary operators are,
Operator Meaning

- Minus

++ Increment

-- Decrement

& Address- of operator

sizeof sizeof operator


 Binary Operator: A binary operator operates on two
operands. Some of the binary operators are,

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modular Division

&& Logical AND


Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is
the ternary operator.
#include<stdio.h>
int main()
{
int a=10, b=3, max;
max= a>b ? a : b;
printf("%d\n",max);
return 0;

10>3 a
Classification based on role of operands

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Miscellaneous Operators
 Arithmetic Operators
 They are used to perform arithmetic operations like
addition, subtraction, multiplication, division etc.

 A=10 & B=20
Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ The division operator is used to find the quotient. B / A will give 2

% Modulus operator is used to find the remainder B%A will give 0

Unary plus & minus is used to indicate the algebraic sign of a


+,- +A, -A
value.
Increment operator
The operator ++ adds one to its operand.
++a or a++ is equivalent to a=a+1
Prefix increment (++a) operator will increment the
variable BEFORE the expression is evaluated.
Postfix increment operator (a++) will increment AFTER
the expression evaluation.
E.g.
c=++a. Assume a=2 so c=3 because the value of a is
incremented and then it is assigned to c.
d=b++ Assume b=2 so d=2 because the value of b is
assigned to d before it is incremented.
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
Prefix decrement (--a) operator will decrement the
variable BEFORE the expression is evaluated.
Postfix decrement operator (a--) will decrement AFTER the
expression evaluation.
E.g.
c=--a. Assume a=2 so c=1 because the value of a is
decremented and then it is assigned to c.
d=b-- Assume b=2 so d=2 because the value of b is
#include<stdio.h>
int main(void)
{
int a=2,b=2,x,y;
x = 4*(++a * 2 + 3);
y = 4*(b++ * 2 + 3 );
printf("a=%d, b=%d, x=%d, y=%d\n",a,b,x,y);
return 0;
}
X=4*(3*2+3)=4*9=36
Y=4*(2*2+3)=28
2. Relational Operators
 Relational operators are used to compare two operands.
If the relation is true, it returns value 1 and if the relation
is false, it returns value 0.
 An expression that involves a relational operator is called
as a condition. For e.g a<b is a condition.
3. Logical Operators
Truth tables of logical operations

condition 1 condition 2 NOT X X AND Y X OR Y


(e.g., X) (e.g., Y) (~X) ( X && Y ) ( X || Y )

False false true false false

False true true false true

true false false false true

true true false true true


Bitwise Operators

 C language provides 6 operators for bit manipulation.


Bitwise operator operates on the individual bits of the
operands. They are used for bit manipulation.
Truth tables
3 << 2 (Shift Left)
0011
1100=12

3 >> 1 (Shift Right)


0011
0001=1
~ 3 (complement)
0011
1100 (12)
5. Assignment Operators

E.g.var=5 //5 is assigned to vara=c; //value of c is assigned to a


6. Miscellaneous Operators

 Other operators available in C are


 Function Call Operator(i.e. ( ) )
 Array subscript Operator(i.e [ ])
 Member Select Operator
 Direct member access operator (i.e. . dot operator)
 Indirect member access operator (i.e. -> arrow operator)
 Conditional operator (?:)
 Comma operator (,)
 sizeof operator
 Address-of operator (&)
Managing Input and Output
operations
 The I/O functions are classified into two types:
 Formatted Functions
 Unformatted functions
Input and Output functions

Formatted Functions Unformatted Functions

printf() getchar()
scanf() gets()
putchar()
puts()
Unformatted Functions
3 types I/O functions.
 Character I/O
 String I/O
 File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
eg:
char c;
c=getchar();
2. putchar() This function prints one character on the screen at a time.
Syntax :

eg
char c=‘C’;
Example Program
#include <stdio.h>
int main()
{
int i;
char ch;
ch = getchar();
putchar(ch);
return 0;
}

Output:
A
A
b) String I/O

1.gets() – This function is used for accepting any string


through stdin (keyboard) until enter key is pressed.
Syntax
gets(variable_name);

2. puts() – This function prints the string or character array.


Syntax puts(variable_name);
Example Program
#include<stdio.h>
int main()
{
char ch[30];
printf("Enter the String : ");
gets(ch);
puts("\n print the String ");
puts(ch);
return 0;
}
Output:
Enter the String : WELCOME to cit\0
Formatted Input & Output
Functions
 When I/P & O/P is required in a specified format then the standard library
functions scanf( ) & printf( ) are used.
 O/P function printf( )
 The printf( ) function is used to print data of different data types on
the console in a specified format.
 General Form
 printf(“Control String”, var1, var2, …);
 Control String may contain
 Ordinary characters
 Conversion Specifier Field (or) Format Specifiers
 They denoted by %, contains conversion codes like %c, %d
etc.
 and the optional modifiers width, flag, precision, size.
Conversion
Data type
Symbol
char %c
int %d
float %f
Unsigned
%o
octal
Pointer %p
E.g: printf(“Number=%.2f\n”,5.4321)
Output: Number=5.43
1.%d or %i for Integer

Size modifiers used in printf are,

Size modifier Converts To

ld Long int

hd Short int
double or Long
lf
double
%ld /li means long int variable
%hd /hi means short int variable
%u address of variable
%u useiged
%x hexa decimal
%d or %i (octal/hexa)for Integer
Input Function scanf( )
It is used to get data in a specified format. It can accept
data of different data types.
Syntax
scanf(“Control String”, var1address, var2address, …);
Format String or Control String is enclosed in quotation
marks. It may contain
1. White Space
2. Ordinary characters
3. Conversion Specifier Field
It is denoted by % followed by conversion code and
#include <stdio.h>
main( )
{
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
sum=num1+num2;
printf("Sum: %d",sum);
}
Output
Enter two integers: 12 11
Sum: 23
Decision Making and
Branching
 Decision making statements in a programming
language help the programmer to transfer the control
from one part to other part of the program.
 Flow of control: The order in which the program
statements are executed is known as flow of control. By
default, statements in a c program are executed in a
sequential order.
 The default flow of control can be altered by using flow
control statements. These statements are of two types.
Branching statements

Branching statements are used to transfer program control from one


point to another.
2 types
Conditional Branching:- Program control is transferred from one point to
another based on the result of some condition
Eg) if, if-else, switch
Unconditional Branching:- Program control is transferred from one point to
another without checking any condition
Eg) goto, break, continue, return
a) Conditional Branching : Selection statements
Statements available in c are
The if statement
The if-else statement
(i) The if statement
C uses the keyword if to execute a statement or set of statements when the logical condition is true.
Syntax:
if (test expression)
Statement;
 If test expression evaluates to true, the corresponding statement is
executed.
 If the test expression evaluates to false, control goes to next executable
statement.
 The statement can be single statement or a block of statements. Block of
statements must be enclosed in curly braces. F
Test

T
Statement
#include <stdio.h>
int main()
{
int n;
printf("enter the number:");
scanf("%d",&n);
if(n>0)
printf("the number is positive");
return 0;
}
(ii)The if-else statementF
T

 Syntax: if (test expression)


Statement T;
else
Statement F;

 If the test expression is true, statementT will be


executed.
 If the test expression is false, statementF will be
executed.
 StatementT and StatementF can be a single or block of
statements.
Example:1 Program to check whether a given number is even or odd.
#include <stdio.h>
int main()
{
int n,r;
printf("Enter a number:");
scanf("%d",&n);
r=n%2;
if(r==0)
printf("The number is even");
else
printf("The number is odd");
return 0;
}

Output:
Enter a number:15
Example:2 To check whether the two given numbers are equal
#include <stdio.h>
int main()
{
int a,b;
printf("Enter a and b: ");
scanf("%d%d",&a,&b);
if(a==b)
printf("a and b are equa");
else
printf("a and b are not equal");
return 0;
}

Output:
Enter a and b: 2 4
 iii) Nested if statement
 If the body the if statement
contains another if statement, then it is This is if
if (test expression1)
known as nested if statement {
ladder
…..
 Syntax: if (test expression)
if (test expression2)
{
{
if (test expression) ….
if (test expression) statement;
if (test expression3)
if (test expression)
{
….
….
statement;
if (test expression n)
else }
}}}
Statement F;

….
iv) Nested if-else statement

Here, the if body or else body of an if-else statement contains another if


statement or if else statement
Syntax:
if (condition)
{
statement 1;
statement 2;
}
else
{
statement 3;
if (condition)
statementnest;
statement 4;
}
Program for finding greatest of 3 numbers

#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("a is greatest");
}
}
else
{
if(b>c)
printf("b is greatest");
else
printf("C is greates");
}
return 0;
}
v) Switch statement

It is a multi way branch statement.


It provides an easy & organized way to select among
multiple operations depending upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements
after that matched case gets executed.
4. If no match occurs, then all the statements after the
default statement get executed.
Switch ,case, break and default are keywords
Break statement is used to exit from the current case
Example1
switch(expression)
{
case value 1:
#include<stdio.h>
program statement;
int main()
program statement;
{
char ch; ……

printf("Enter a character\n"); break;


case value 2:
scanf("%c",&ch);
program statement;
switch(ch)
Program statement;
{
……
case 'A':
break;
printf("you entered an A\n"); …
break; case value n:

case 'B': program statement;

printf("you entered a B\n"); program statement;

break; ……
default: break;
printf("Illegal entry"); default:

program statement;
break;
} program statement;
}
return 0;
Example2
#include<stdio.h>
int main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
switch(n%2)
{
case 0:printf("EVEN\n");
break;
case 1:printf("ODD\n");
break;
}

return 0;
}

Output:
Enter a number
5
ODD
b)Unconditional
branching statements
i)The goto Statement
This statement does not require any condition. Here
program control is transferred to another part of the
program without testing any condition.
Syntax:
goto label;
label is the position where the control is to be transferred.
#include<stdio.h>
int main()
{
printf("www.");
goto x;
y:
printf("mail");
goto z;
x:
printf("yahoo");
goto y;
z:
printf(".com");
return 0;
}
b)break statement
A break statement can appear only inside a body of , a switch or a loop
A break statement terminates the execution of the nearest enclosing loop or switch.
break;

#include<stdio.h>
int main()
{
int c=1;
while(c<=5)
{
if (c==3)
break;
printf("\t %d",c);
c++;
}
return 0;
}
Example :2
#include<stdio.h>
int main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(" %d",i);
}
return 0;
}
iii) continue statement
A continue statement can appear only inside a loop.
A continue statement terminates the current iteration of the nearest enclosing loop.
Syntax:
continue;
Example :1
#include<stdio.h>
int main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(" %d",i);
}
return 0;
}
iv) return statement:
A return statement terminates the
execution of a function and returns the control to
the calling function.
Syntax:
return;

(or) return expression;


TEXTBOOKS:
1. Pradip Dey and Manas Ghosh, ―Programming in C, Second Edition,
Oxford University Press, 2011.
2. Ellis Horowitz, Sartaj Sahni, Susan Anderson-Freed, ―Fundamentals
of Data Structures in C, Second Edition, University Press, 2008.
REFERENCES:
1. Mark Allen Weiss, ―Data Structures and Algorithm Analysis in C,
Second Edition, Pearson Education, 1996
2. Alfred V. Aho, John E. Hopcroft and Jeffrey D. Ullman, ―Data
Structures and Algorithms, Pearson Education, 1983.
3. Robert Kruse, C.L.Tondo, Bruce Leung, Shashi Mogalla , ― Data
Structures and Program Design in C, Second Edition, Pearson
Education, 2007
OU
Y
N K
H A
T

You might also like