Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
156 views

C Programming: R V Yenkar Hod Ec & It G P Nagpur

The document provides an overview of input and output operators in C programming. It discusses that C does not have built-in input/output statements and all I/O is done through functions like scanf() and printf(). It then explains the scanf() function for input operations, describing its general format and various format specifiers for reading different data types like integers, floats, characters, and strings. Examples are given to illustrate how to use scanf() to read mixed mode data from the console.

Uploaded by

zaheeda1984
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
156 views

C Programming: R V Yenkar Hod Ec & It G P Nagpur

The document provides an overview of input and output operators in C programming. It discusses that C does not have built-in input/output statements and all I/O is done through functions like scanf() and printf(). It then explains the scanf() function for input operations, describing its general format and various format specifiers for reading different data types like integers, floats, characters, and strings. Examples are given to illustrate how to use scanf() to read mixed mode data from the console.

Uploaded by

zaheeda1984
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
You are on page 1/ 101

C Programming

R V Yenkar
HOD EC & IT
G P Nagpur
Chapter 1

IMPORTANCE OF ‘C’ LANGUAGE


Origin of C

• BCPL developed - MARTIN RICHARDS


• B Language developed - Ken Thompson in 1960
• C Language developed – Dennis Ritchie in 1970
– Bell Laboratories
– Initially It works in UNIX platform only.
– Now it works in MS-DOS & Windows platforms.
– Most popular programming Language

3
Significance of C
• C often termed as ‘middle level Language’
• Types programming Languages
– Machine level (Low level)- Assembler
– Middle level - C, Micro-Assembler
– High level – BASIC, PASCAL, FORTRAN, COBOL
• It combines the features of both high & low
level languages.

4
C is a system programming language
• It is a blend of both high & low level languages.
• It can directly interact with microprocessor.
• Execution time will be comparatively low

C is highly portable
• It allows the manipulation of bits, bytes and
address – Computer element
• Portability means adaptability between
different computers.
• Program written in C is easily transferable from
DOS to UNIX & vice versa.
5
C is a programmers language
• High level language program can understand by non-
programmers & allows them to alter it .
• C programs has few restrictions, compact set of
keywords, block structures thus non-programmers
can’t understand .
• C environment suits for professional programmers.

C has easy Coding


• C has easy coding property.
• C takes less number of lines code as compared with
other high level language.
• C is equipped with a rich set of operators and built in
functions.
6
C is structured language
• Structured programming means modular
programming.
• Main structural component are
– Function (sub programs, sub routines)
– Code blocks( between pair of braces)
– Program can be written without GOTO statement
• It supports library functions & has strong in-built
library.
• User can add own library functions

7
Programming Steps
• Creating the program
• Compiling the program
• Linking the program with functions that are
needed from library
• Executing the program

8
General form of C Program
• Comments
• Declarations: •It provides more freedom to
 # include statements
 #define statements
programmer.
 Global variables •Must have one or more functions
• Main program
main() •Each function have variables &
{ statements.
Variables;
Statements; •Every program must have main()
} function & it is the first function called
• Sub program
function1() for execution.
{ •Pair of braces are used at
Variables;
Statements; appropriate places to distinguish
} functions / code blocks.
function2()
{
•Program start with open brace &
Variables; ends with closing brace.
Statements;
}
•Statement must end with
9
semicolon.
REVIEW (Points to be remembered)
• C is middle level language.
• C is a portable, structured language, has easy
coding & it is a programmers language.
• Comparatively C programs run faster.
• C program is made of many (user/ built-in)
functions & code blocks
• Every program begins with main() function &
execution starts only from that.
• Each function / code block start with opening brace
& ends with closing brace.
• Each program statement must end with semicolon.
• C program can run in UNIX, MS-DOS & Windows
platforms.
10
GOTO Next Topic

11
Chapter 2

Fundamentals of ‘C’ Language


Introduction
• What are basic requirements of any language?
 Character set
 Vocabulary
 Grammar
• What is programming language?
 A programming language is designed to process
certain data & produce useful output known as
information.
 The task of processing of data is accomplished by
executing a sequence of instruction is called program.
13
Character set
• Letters:- A to Z, a to z. Usually program
statements in lower case. Case sensitive.
• Digits:- consists from 0 to 9.
• Special Characters:-
, ; : ? ‘ “ / \ _ !
% + - < > $ ~tilde,
&ampersand, ^ caret, *asterisk, |vertical bar,
#hash, { } braces, ()parenthesis, []brackets,
• White spaces:- blank space, new line, carriage
return, tab.

14
C Token
• Identifiers
• Keywords
• Operators
• Literals
• White spaces

15
Identifiers
• Variables
• Constants
• Function
 first character of identifier will be
alphabet followed by either number or
alphabet. Underscore is only allowed.
Length 31 characters
volume, 1area, area_plus, _area1
16
Data Types
• Four basic data types
– Integer,
– Character,
– Float,
– Void
• Types modifiers :-
– Integer  signed, unsigned; long, short.
– Float float, double, long double

17
Integer
• Number without decimal point
• C doesn’t permit unary + sign
• Signed integer:– 2 bytes, -32768 to 32767
• Unsigned integer:– 2 bytes, 0 to 65535
• Long integer:– 4 bytes, -2147483648 to
2147483647
• Unsigned long integer:– 4 bytes, 0 to 4294967295
• Short integer:– 1 bytes, -128 to 127
• Unsigned short integer:– 1 bytes, 0 to 255
18
Float
• Number with decimal point
• Float – up-to 7 decimal points
• Double up-to 12 decimal places
• Long double up-to 16 decimal places
• Floating – mantissa & exponent part

19
Variables / constants
• A variable is the storehouse for constants
• Value may change throughout program
• All variables must be declared before used
– Format
Data-type variable_list;
Short area;
Int a,b,c;
Int d=10; /* initialize the value */
• Value does not change throughout program
is called constant.
Const b=5;
20
Character
• Any single letter enclosed within single
quote
Char v_name;
v_name =‘a’;

Void
•It is valueless.
•Uses – declare function that returns no
value. Create generic pointers.
21
Keywords
• int long short signed unsigned float double
char void const typedef
• if else while do for switch case goto
continue break struct union
• Auto default enum extern register sizeof
static voiatile return

22
GOTO Next Topic

23
Chapter 3

Input & Output operators


INTRODUCTION

• C language does not have any built-in input/output


statements.
• All I/O operations are carried out through function
calls such as scanf() and printf()
• These function calls collectively called as Standard
I/O Library
Input data

101.75 225 R

float int char

The above line contain 3 pieces of data arranged in


a particular format using scanf() function

26
Input operations:- scanf() Function
• General purpose console input function.
• Used to input a data line containing mix
mode data.
• General form
scanf( “format specifier”, variable list)

e.g.
scanf(“%d%d%d”, &A, &B, &C);
27
Format specifier
Code Meaning
%c To read single character
%d To read a decimal integer
%e To read a floating point value
%f To read a floating point value
%g To read a floating point value
%o To read an octal value
%x To read a hexadecimal value
%s To read a string
%u To read an unsigned integer
28
For reading integer : %xd
Data type
characer
Conversion Specify field
character width

Ex.
scanf(“%d%d “, &a, &b);

If Input data is 7 9
then a=7 and b=9

29
For reading float numbers : %xf

Data type
Ex. characer

scanf(“%f%f “, &a, &b);

If Input data is 179.23 4.38


then a= 179.23 and b= 4.38
30
For reading characters and string :
%xc %xs

character string
Ex. Ex.
scanf(“%c%c “, &no1, &no2); scanf(“%s “, name);

If Input data is R S If Input data is welcome


then no1=R and no2=S then name=welcome
Note : no ‘&’ sign before identifier
31
For reading mixed data types :
Ex.
scanf(“%d%c%f%s “, &a, &b, &c, d);

If Input data is 7 p 125.34 hello


then a=7
b=p
c=125.34
d=hello
32
scanf() features
1. Format specifications and variable list
must correctly match
2. Format specifier must be separated by
no-space and variable list by comma
3. Use of invalid match terminate reading
data
4. Field width specifier ‘w’ must be used
with appropriate specification to match
corresponding data size

33
Output operations:-printf() Function
• Output statement to display the o/p such
as captions, numerical results, etc.
• General form
printf( “format specifier”, variable list)
e.g.
printf(“%d %d %d”, A, B, C);
Display values for A, B, C
printf(“%d %d \n ”, a,b);
Display values for a, b and cursor will move to new line for
next printing
34
Other escape sequences
Codes Meaning
\b Back space
\f Form feed
\r Carriage return
\t Horizontal Tab
\” Double quote mark
\’ Single quote mark
\0 Null
\\ Back slash
\v Vertical tab
\a Alert
\o Octal constant
\x Hexadecimal constant
\n New line
35
Chapter 4

Operators & Expressions


operators
• Arithmetic operators
• Auto increment / decrement operators
• Assignment operators
• Relational operators
• Logical operators
• Ternary operators
• Cast operators
• Bitwise operators
• Special operators 37
Arithmetic Expression
• An arithmetic expressions a combination of
variables, constants & operators.
• ‘c’ doesn't have an operator for
exponentiation. (i.e. to express power of)
• AxB-C A*B-C
• (M+N)(X+Y) (M+N)*(X+Y)
• AB/C A*B/C
• 3X²+2X+1 3*X*X+2*X+1
• Evaluated using assignment statement.
• First evaluation & then value assignment.
38
Rules for Evaluation of Expression
• First parenthesized sub expression from LR
• Nested parentheses, first innermost.
• Arithmetic expressions evaluated form LR
Precedence Rules
1)Unary operator -,++,-- ! sizeof() RL
2) * / % LR ;
3) + - LR;
4)Relational operator LR
5)Logical LR
6)Assginment operator +=,*=,-=,/= RL 39
Chapter - 5

Decision Making
and
Branching
Introduction
• Normally program is executed in
sequentially in the statement appears.
• In some situation
→ we need to change the order of execution
based on certain condition.
→ repeat a group of statement until specified
condition get satisfied.
→This involves in decision making statements &
controls the sequence of execution; thus also
called control statements.

41
Introduction
• Different decision making & branching
statements are as follows
 if statement
 switch statement
 ternary operator statement
 goto statement

42
Decision making with if statement
if statement is powerful decision making statement
and is used to control the flow of execution.
Entry

Test False
expression
?

True
43
Examples of decision making
1. if (room is dark)
put on light.
2. if (bank balance is zero)
borrow money
3. If (age is more than 60)
person is retired
4. If (marks less than 35)
student is fail
5. If (b < a) b is less
else a is less
44
Forms of if

• Simple if statement
• If……else statement
• Nested If……else statement
• else if ladder

45
Simple if statement
Entry

If (test expression)
Test True
{ expression
statement block; ?
Statement
} block
False
Statement-x;

Statement-x

Next-Statement
46
……..
……..
If (category == “SPORTS”)
{
marks = marks + bonus_marks;
}
Printf(“%f”, marks);
……..
……..

47
If……else statement
Entry
If (test expression)
{
Test
true-block statement(s); False True
expression
?
}
False-block True-block
else Statement Statement
{
false-block statement(s);
}
Statement-x
Statement-x;

48
……… ………
……… ………
If (code == 1) If (sales >= 30000)
{ {
boy = boy + 1; commission = sales * 0.08;
} }
else else
{ {
girl = girl + 1; commission = sales * 0.05;
} }
……… ………
……… ………

49
Nested If……else statement
Entry

Test
False True
Condition 1
?

False Test True


Condition 2
?

Statement-3 Statement-2 Statement-1

Statement-x
50
If (test condition-1) If ( candidate is female)
{ {
If (test condition-2) If ( balance > 5000)
{ {
statement-1; bonus = balance * 0.05;
} }
else else
{ {
statement-2; bonus = balance * 0.02;
} }
} }
else else
{ {
statement-3; bonus = balance * 0.02;
} }
Statement-x; balance = balance + bonus;

51
else if ladder
Entry

True Test False


Condition 1
?

Test False
Statement-3 True Condition 2
?

Statement-2 Test
True False
Condition n
?
Statement-n Default
statement

Statement-x 52
Example: If ( avg > 79 )
grade = “Honours”;
Average Grade
else if ( avg > 59 )
marks
80 to 100 Honours grade = “First Div”;
60 to 79 First Div else if ( avg > 49 )
50 to 59 Second Div grade = “Second Div”;
40 to 49 Third Div else if ( avg > 39 )
0 to 39 Fail
grade = “Third Div”;
else
grade = “Fail”;
Printf(“%s \n”, grade);

53
The switch Statement

•Switch is a multi-way decision statement


•Switch statement tests the value of a given
variable (expression) against the list of case
values.
•When match found, block of statement
associated with that case is executed.
•Expression/value is integer or character
General form of switch statement
index=per/20;
switch (index)
switch (expression) {
{ case 5:
case value1: case 4:
grade=‘A’;
block1;
break;
break;
case 3:
case value2:
grade=‘B’;
block2;
break;
break;
case 2:
---------------- grade=‘C’
default: Break;
default-block; Default:
break; grade=‘F’
} break;
} 55
Chapter - 6

Decision Making
and
Looping
• In looping, a sequence of statements
are executed until some conditions
for termination of the loop are
satisfied.
• Program loop consists of 2 segments
– Body of the loop
– Control statement

57
Pre-test loop
Entry

Test False
condition
?

True

Body of the Loop

58
(a) Entry control
Entry Post-test loop

Body of the Loop

Test False
condition
?

True

59
(b) Exit control
The C language provides 3
constructs for performing
loop operation

• The while statement


• The do statement
• The for statement

60
The while statement
while (test condition)
{
body of the loop
}
Statement-x; ==========
sum = 0 ;
n = 1;
while ( n <= 10 )
========== {
chr = ‘ ‘ ; loop printf(“%d \n”, n);
while (chr != “Y”) sum = sum + n;
{ n = n + 1;
chr = getchar();
}
}
printf(“Sum = %d \n”, sum);
xxxxxxxxx ; 61
==========
==========
The do statement
do
{
body of the loop
}
while (test-condition);
==========
========== sum = 0 ;
do i = 1;
{ do
printf (“Input a number \n”); {
number = getnum(); sum = sum + i;
} loop i = i + 2;
while (number > 0 ); }
xxxxxxxxx ; while ( i <= 10 || sum<50 )
========== printf(“Sum = %d \n”, sum);
========== 62
The for statement
for (initialization ; test-condition ; increment)
{
body of the loop
}

==========
sum = 0 ;
for ( n=1; n<=10; n=n+1)
{
loop sum = sum + n*n;
}
printf(“Sum = %d \n”, sum);
==========

63
Comparison of the 3 loops
n=1; n=1;
while (n<=10) do
{ {
-------- --------
-------- --------
n=n+1; n=n+1;
} }
while (n<=10);

for (n=1 ; n<=10 ; ++n)


{
--------
--------
} 64
Nested loop
• A loop inside a loop.
• Two or more conditions need to be tested
at time.
• Depending on the situation choose a
particular loop.
– For loop if counter controls the loop
– Do-while loop if exit level control is needed
– While loop if entry level control is needed.
• Any combination of loop’s can used as per
the need
65
Nested loop
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
j=1;
for(j=1;j<=3;j++)
do
{ {
inner loop statements; inner loop statements;
j=j+1;
}
}
outer loop statements;
while(j<=3);
} outer loop statements;
}
66
Structured Programming

• Structured programming is an approach to the


design and development of programs.
• It is a discipline of making a program's logic easy to
understand by using only the basic 3 control
structure :
1. Sequence (straight line) structure
2. Selection (branching) structure
3. Repetition (looping) structure
• Structured programming discourages the
implementation of unconditional branching using
jump statements such as goto, break and
continue.

Do not go to goto
statement!  67
Next :

Jumping in loop

Jumping out of loop

Skipping a part of a loop

68
Chapter 7

ARRAYS
INTRODUCTION
• Fundamental data type – char, int, float
• Variables of these types can store only one
value at a time. New value can be stored
after erasing previous value.
• To store ‘m’ number of data we need ‘m’
number of variables.
• m=5 (5 values) 5 variables
int m1,m2,m3,m4,m5;
• m=100 (100 data) 100 variables
int m1,m2,………………………………,m100;
int m[100];
70
Data Structures

• C supports a rich set of derived & user defined data


in addition to fundamental data types.

Data types

Derived User
fundamental
type defined
type
type

Array Integer structure


Function Float union
pointers Character enumerations
 Array & structure are also called data structure.
Other data structures are link-list, tree, stack, queues
71
What is an array?
• An array is a collection of variables of same
data type that are referenced by a common
name.
• An array can be used to store a list numbers,
a list of character or list of strings.
• Examples
– List of students
– Test score of a class of students
– Marks obtained by a class of students in all subjects
– Table of daily rain fall data.
72
Examples
List of students
• Let us consider a class have 30 students
• To store marks obtained by these students in
English.
int english[30];
• For this system will allocate 30 memory locations for
identifier english.
• english[0], english[1],……..,english[29]
• Here index starts form 0 & goes upto 29.
• Complete collection is array & the individual values
are called elements.
• Specific elements are referred as index of subscript.
• Array may one, two or many dimensions.
73
One dimensional Array
• This is also called as “list”
• General form of single-dimensional array is
Data_type array_name[size];
int a[5]; /*array having 5 elements*/
These are a[0] a[1] a[2] a[3] a[4]
0th 1st 2nd 3rd 4th
Examples
int mark[10]
float age[20]
char name[20] 74
Array initialization
• C permits initialization of arrays at the time
of declaration. The general form of it as
Data-type array-name[size]={ value list };
Note – value list must be separated by comma
whose value is compatible with data type.
(eg)
int a[5]={1,2,3,4,5};
float p[3]={1.2,5.4,3.2};
int b[]={1,1,2,2,3};
Int sum[5]={4,8,5}; /* remaining are set to zero*/
75
Problem
• Program to find maximum number in an array
Solution
#include <stdio.h>
#include<conio.h>
main()
{
clrscr();
int a[6],i,max;
printf(“enter 6 numbers”);
for(i=0;i<6;i++)
scanf(“%d”,&a[i]);
max=a[0];
for(i=1;i<6;i++)
if(max < a[i])
max=a[i];
printf(“\n the max no in an array is %d”,max);
getch();
}
76
Explanation
• First get 6 elements & store them in an array ‘a’.
• First value (0th element) is assigned to identifier ‘max’.
• Then compared with a[i] element array; where i1 to 6
– If a[i] is greater than max
• then max is replaced with this number
• otherwise retain it.
– Repeat it for all values.
• Print the result.

77
Two dimensional Array
• Two dimensional Array is array of array.
• Two dimensional Array can store a table of
values.
• The general form
Data-type array-name[row-size][column-size];
int a[3][3] will have elements are
a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
78
Initialization of 2D array
• Similar to 1D array, 2D array can be
initialized.
– int a[2][3]= { 1,1,1,2,2,2 };
– Here first row is initialized to 1& 2nd array to 2.
– int a[2][3]= { 1,1,1 },{ 2,2,2 };

Problem
For 2D array of 3X3, Find the following
1. Sum of all elements.
2. Row wise sum
3. Column wise sum
79
Multi-dimensional array
• C allows more than 2D array
• The general for of Multi-dimensional array is
– Data-type array-name[a][b]……….[z];
• Multi-dimensional arrays occupy more memory
space.
Problem
Consider there are 2 semesters, each semesters has got 4
subjects & the mark in each subject is the sum of 3 test
result.
Array 1D - 2 semesters
Array 2D – 4 subject/semester
Array 3D - three test /subject
80
Chapter 8

Character Handling in C
String
• A string is an array of characters.
• A group of characters defined between
double quote mark is a string.
• To build more readable program, strings
are required.
• Reading & writing
• Combining two strings together.
• Copying one string into another string.
• Comparing two string
• Extracting a portion of a string
82
Declaring of string variables
• String is defined as character array.
• General form
char string-name [size];
– char sname[30];
– char country[20];
• It is terminated by a null. ‘\0’ & for this size
of string =actual size +1.
– dharamadhikari  14 char ; size = 14+1=15
– char name[15];
83
Reading a string
• char name[15];
• scanf(“%s”,name); // don't use ampersand sing //
Let we want to read “New Delhi” as a city name.
– char city[10];
– scanf(“%s”,city); 
The scanf() has got limitation that it terminates its input
on the first white/blank space it encounters.
– char city1[10],city2[10];
– scanf(“%s %s”,city1,city2);
– char city[10];
– gets(city); //to read more word in a single string//
84
Writing strings

• char name[15];
• printf(“%s”,name);
• puts()  to write characters.

85
String Functions
• String handling using library functions
#include<string.h>
• strcpy(st1,st2)copies st2 into st1.
• strlen(st1)  returns length of string.

86
Chapter 9

Function
User defined function
• C is language of functions
• Function like main() scanf() printf() are
called library functions.
• One main strong factor of C is the user
defined functions
• C functions are very easy & versatile.
• What is the difference between these two
functions?

88
What is a ‘C’ function?
• A function in is considered as a fundamental
building block.
• In order to avoid the complexity of a program
while coding, debugging & testing; the program
is divided into function parts or subprograms.
• Each module is called a function.
• ‘C’ allows to declare a function prototype.
• From function prototype, we get number & type
data that function is expect & type of value it
returns.
• int sum(int x,int y)
89
General form of function
• The general form of ‘C’ function
Return-data-type fun-name( argument-declaration);
{
Local variable declaration;
Body of the function;
return (expression);
}
Return data type specifies the type of value that function
returns after execution of return statements.
1.int I, j, dot();
// Here function dot() returns integer value//
2.float a, b, sum();
// Here function sum() returns float value//
90
General form of function
• Example 1 • Example 2
void main() void main()
{ {
void errormsg(void); int a, b, cube(int);
| scanf(“%d”,&a);
Statements; b=cube(a);
| printf(result=%d”,b);
errormsg(); }
}
int cube(int x)
void errormsg(void) {
{
printf(“Error”); int y;
} y=x*x*x;
return(y);
}
91
The return statement

• The return statement


– Causes an immediate exit from the function
– Returns the value.
• When it encountered, the control is passed
back to calling function.
return;
return(value);
return(expression);
92
Chapter 10

Structure
Introduction

• Array & structure are derived data type.


• Array can be used to represent a group of
same data type only. Can’t be used for
collection of different data types.
• Under above situation “Structure” or
“Union” is used.

94
What is a structure?
• A “structure “ is collection data item (fields)
or variables of different data types that are
referred under the same name.
• It provides convenient means of keeping
related information together.
• The general form
struct tag-name
{
data-type members;
} 95
What is a structure?
• “struct” is a keyword, used to declare
structure template.
• Tag-name identifies the particular structure
& its data types.
• The fields in structure is structure elements
• All elements are logically related to each
other.

96
Example
struct stdrec
{
char name[15];
char examno[10];
int eng, maths, phy, chem;
};

97
Chapter 11

Pointers
Introduction
• Pointers are one of the most important
features of c language.
• In scanf() we have used pointer.
• All variables stored have its address in the
memory.
• Pointers are used for this purpose & it has
its own benefits.
• Pointers will make the program more
efficient.
99
What is pointer?
• It is a variable, which store the address of
another variable.
• A variable contain the address of another
variable then first variable is said to point
the second variable.
• Pointer operator – to determine the
address of a variable, there are two
operators ‘&’ and ‘*’
– & is “address of” operator
– * is “content of” operator.
100
Pointer
• The general declaration form is
– Data-type *variable-name;
– In above declaration 3 aspects are conveyed.
• The ‘*’ tells that variable-name is pointer variable.
• The pointer variable needs a memory location
• The pointer variable points to a variable of type
“data-type”.
– Examples
• int *a; //a is pointer variable points to an integer data type.
• float *b; //b is pointer variable points to afloat data type.

101

You might also like