Upload
others
View
17
Download
0
Embed Size (px)
Citation preview
Class FE Division: P
Unit 1 to Unit 3(As per revised Syllabus 2013-14)
Compiled by : Jayesh Bhangdiya
Let Us C Book and PPTs by Yashwant Kanetkar
Computer Fundamentals by Pradeep Sinha
Prof. Vishal Kaushal
Prof. Saurabh Khatri
To all other many references used.
Unit 1:
• Introduction to Programming
• Introduction to C
Unit 2:
• Flow of control
• Functions
Unit 3:
• Arrays
• Strings
Unit 4:
• Pointers
• Structures
Unit 5:
• Recursive Functions
• Sorting and Searching algorithms
“Let us C”, Y. Kanetkar, Second Edition, BPB Publication.
ISBN: 8176566217.
“Programming with C- Schaum‟s outline Series”, B.
Gottfried, Second edition, Tata McGraw Hill Publication,
ISBN 0-07-463491-7
“Programming language – ANSI C”, Brain W Kernighan
and Dennis Ritchie, Second edition ISBN 0-13-110370-9,
Directly sits on top of the hardware and controls it
Provides user with an interface or a virtual machine• More convenient to use than bare machine
Convenience + Resource managementMain functions
• Process mgmt• Memory mgmt• File mgmt• Security• Command interpretetion
Microsoft Disk Operating System
Single user OS for IBM and IBM
compatible PCs
Structured in 3 layers• BIOS
• Kernel
• Shell
Replaced by Windows OS
Developed in early 1970s at Bell Labs by Ken Thompson and Dennis Ritchie
Written in CMulti-user, time-sharing OSUsed on wide variety of computersStructured in three layers
• Kernel
• Shell
• Utilities
LINUX – similar, yet different
Machine Language Consists of combination of 0’s and 1’s that
represent high and low electrical voltage.
• Unsuitable for programming, difficult to
program.
• Machine dependent.
• Error prone.
• All programs are converted into machine
language before they can be executed.
Assembly Language• Similar to Machine level but replacing 0s and 1s
with Names and symbols
• Also known as Object code
• Uses symbolic codes to represent the machine operation code
• More readable
• Can be used to write instructions.
• Ex: ADD ------- 3E, etc
• Platform Dependent
• .obj extension
High-Level Languages
Programming languages that are easier
to learn.
Uses English like statements.• Readable familiar notations
• Availability of program libraries
• Platform Independent.
• Hides the details of computer.
• Example C language (.c extension)
High Level source
code(.c)
Middle level object
code(.obj)
Low level executable code(.exe)
Assemblers• Assemble to Machine
• Source Program to Object Program (one to one)
Compilers• High-level to Machine
• Source to Object (one to many)
• Separate compiler for each HLL on same comp
or same HLL on different computer
Linkers• Large programs span multiple source files
• Each source file can independently be translated into corresponding object files (modules)
• Linker combines them appropriately and creates a final executable
Loaders Interpreters
• One by one translates and executes the instruction with the input
Hybrid approachCompiler first compiles source code into
intermediate object code• Machine code for a “virtual” machine
• Based on standard IDL
Interpreter takes this object code and coverts it into and executes the machine code
Another variant – JIT compilation• Compiling the intermediate program
Plan of a computer program• Logic
• Step by step description of how to arrive at the
solution of a given problem
Algo representations• Program
• Flow chart
• Pseudo code
Also called Program Design Langauge (PDL)
Each and every instruction should be
precise and unambiguous
Each instruction should be able to be
executed in finite time
One or more instructions should not be
repeated infinitely• It should ultimately terminate
Desired results must be obtained after
termination
Pictorial representation of an algorithmUses standard symbols to represent
different meaningsActual instructions written within boxesBoxes are connected by arrowsFlowchartingMacro flowchart and micro flowchartAdvantages
• Better communication/documentation
• Efficient coding
• Systematic debugging and testing
Middle-level language• High level programming language with efficiency of assemble
language Developed in 1972 at AT&T‟s Bell Laboratories by
Dennis Ritchie and Brian Kernighan Standardized by ANSI and ISO Salient features
• User-defined data types
• Modular and structured programming concepts
• Rich library of functions
• Pointers and pointer operations
• Low-level memory and device access
• Small and concise
• Used for applications as well as systems programming
One or more modules called functionsCombination of statements between {
and }Null statement
• ; or {}
Simple statement is terminated by a semicolon
Compound statement or statement blockStandard library and header filesPreprocessor directives
Preprocessor is a program that prepares
a program for the compiler
Common directives• #include – import contents from another file
• #define - macros
• #ifdef…#else …#endif – for conditional
compilation
Name and type
Memory location
Can have 1 to 31 characters
Only alphabets, digits and underscore
allowed
Names are case sensitive
First character must be alphabet
Keywords are prohibited• 32 in number
Value never changesPrimitive constants
• Integer 8, +17, -6
Allowable range
• Real 8.6e5, +4.3E-8
Allowable range: -3.4e38 to 3.4e38
• Character „a‟, „%‟
LiteralNamed
C program
int count;
Short index;
C has no keywords for I/O operations
Standard library functions
\n, \t
Typically 10 zones of 8 columns each
“tab stops”
Less commonly used• \b, \f, \‟, \\, \r, \a, \”
Declared within the block and are local to the block
Lives as long as control is in that blockDefault storage class
• Includes formal argument declarationsMemory is allocated automatically upon
entry to a function and freed automatically upon exit from the function - stack
If explicitly initialized, it will be re-initialized each time
If not, the value will be garbage
Stored in register• Hence provide certain control over efficiency of the
program Variables which are used repeatedly or whose
access times are critical may be declared to be of storage class register
Variables can be declared as a register as follows
Everything else remains the same as auto Not guaranteed!
• Falls back to auto Not every type can be stored!
• falls back to auto
Static automatic variables continue to exist even after the block in which they are defined terminates. • Thus value is retained between function calls
Default initial value = 0Scope is local but life is as long as the
program lives Initializer is executed only onceDo not get created on stack, but in a
separate segment of memory called “data segment”
Scope: “global” Life: from point of definition through the remainder of
the program Defined outside of all functions
• Before or after, doesn‟t matter
• However, if you have to use before defining, then declare once more by using extern keyword
Variable defined in one file can be used in another by declaring as extern in the latter
• Best practice – include these in a header file and #include it Default initial value = 0 Static variable can also be declared outside all
functions• Treated as extern, but scope limited to that file only
Const - to explicitly insure that the value
is not changed, even accidentally
Volatile• Compiler may optimize by storing in register
• If you want new value to be loaded from memory
rather than register and stored back
• Especially used when values can be altered by
external entity
Short >= 2 bytes
Long >= 4 bytes
Short <= int <= long
These are used to make programs more
efficient
Short => short int
Long => long int
Free up the sign bit and almost double
the max value permitted • Explicitly call it “unsigned”
Default signed
Arithmetic
Logical• &&, ||, !
Relational• >, >=, <, <=, ==, !=
Order in which different operations are
performed
x+y*z
Order of evaluation when operators of
same precedence appear in an
expression
a=b=c=15
How to compile and execute programs
using command line in DOS
Use of vi and gcc in LINUX
Conversion of numbers in decimal, octal
and hexadecimal form
Control Statements / Branch Statements
IF-ELSE
Nested IF-ELSE
Conditional Expression
Switch statements
If (expression)• Statement1
Else• Statement2
Else is optionalDifference between only if and if-elseUse braces and indents to avoid mistakesScope of if and scope of elseNon zero means trueCoding shortcuts
• (expression) vs (expression != 0)• (!expression) vs (expression == 0)
Int I;
Printf (“Enter value of i “);
Scanf (“%d”, &i);
If (i==5);• Printf(“You entered 5\n”);
Return;
Who does the “else” belong to?
if (n>=0)• for (i=0; i<n; i++)
if (s[i]>0) {
printf(“something”);
return i;
}
else • printf( (“error: n is negative”);
Weather DetectorBetween 0 to 10
• Very cold!10 to 20
• cool20 to 30
• Pleasant
30 to 40• Hot
Three ways of implementing this!Please note, logical operators are short-
circuit
Multi-way decision if (expression)
• statement
else if (expression)• statement
...else
• statement
Last else is optional Improves efficiency – by skipping
evaluation
expression1 ? expression2 : expression3
Not only for arithmetic statements but for
others as well
Supports nesting
Watch out!• a>b?g=a:g=b;
It is an expression – can be used
wherever an expression can be used
Can you print – “You have x items”
Multi-way decision Only to match different constant integer values All case expressions must be different All subsequent statements are executed, until
break or return is encountered• Fall through – both boon and curse
What if there is no “default” “cases” and “default” can occur in any order Good practice – always put “break” after last
clause• Defensive programming
Switch may be nested
Multiple statements do not need to be in braces What happens when there is a statement without
“case”?• No error, but never gets executed
Disadvantage: you cannot have something like• Case i<=20:
Constant expressions can be used in case• Case 3+7: legal
• Case a+b: illegal
Switch is more efficient than equivalent if-else –especially when there are many cases
Loop statementsPre-test
• Condition is tested before each iteration
Post-test• Condition is tested after each iteration
FOR• Initializer
• Loop condition
• Incrementer
WHILE – has only loop conditionDO-WHILE
for (expr1; expr2; expr3)• statement
Scope of for is the immediate next statement All three are optional – but semicolons are
necessary for (i=0; i++<10;)
• printf(“%d\n”, i); Initialization, condition and increment can be any
expressions comma operator
• a pair of expressions separated by comma are evaluated left to right and the type and value of result is type and value of right operand
for (i=0; i<10; i++);• printf(“%d”, i);
while (expression)• statement
Same as saying – while (expression != 0)
For is usually preferred when
initialization and increment are single
statements and logically related
Unconditional branch GOTO label
• Transfer to statement marked with the label within the function
BREAK• Exit from innermost for, while, do or switch statements
• Control is transferred to statement immediately after the block in which break appears
CONTINUE• Skip to next iteration of for, while or do construct
• Control is transferred to statement beginning the block
RETURN
Label must be located in current functionContinue can appear only inside an
iteration statementBreak can appear only inside iteration or
switch statementAvoid goto
• Obscures flow of control
• Take the control to outer loop, deal with error condition
• Better to use more elegant ways
C program is a collection of one or more functions• Only one => main
A function have three things• Return type
• Name
• parameters
Prototype declaration Definition Call Any function can be called from any other function Function call sequence Function cannot be defined inside another function
A function can call itself• Recursion
Procedure Abstraction• Focus on “what” instead of “how”
Implementation Hiding
Modular Programs
Libraries
Function declaration
Parameter names are optional
Return type
Name
Number, type and order of arguments
return-type function-name (parameter decl) {• Declarations
• statements
}dummy(){}Can appear in any order in one source file or severalone function can‟t be split in mutliple
files
main( ){
printf ( ”\n I am in main” ) ;}
bombay( ){
printf ( ”\n I am in Bombay” ) ;}
kanpur( ){
printf ( ”\n I am in Kanpur” ) ;}
Output:I am in main
Functions
main( )
printf( )
scanf( )
getch( )
exit( )
gotorc( )
clrscr( )
for( )
while( )
if( )
switch( )
printf( )
scanf( )
exit( )
clrscr( )
kanpur( )
bombay( )
Std. Library User-Defined
Functions
main( ){
printf ( ”\n I am in main” ) ;
bombay( )
{
printf ( ”\n I am in Bombay” ) ;
}
kanpur( )
{
printf ( ”\n I am in Kanpur” ) ;
}
Output :
I am in main
I am in Bombay
I am in Kanpurbombay( ) ; kanpur( ) ;}
Function Call
Function Def.
A C program is nothing but a collectionof 1 or more functions
If C program contains 1 function its name
must be main( )
If C program contains more than 1 function
then one of them has to be main( )
Execution of any C program always begins
with main( )
Function names in a program must be unique
bombay( ){
printf ( ”\n I am in Bombay” ) ;}main( ){
printf ( ”I am in main” ) ;bombay( ) ;
}
Tip: Functions can be defined in any order
main( ){
printf ( ”\n I am in main” ) ;bombay( ) ;bombay( ) ;
}bombay( )
{printf ( ”\n I am in Bombay” ) ;
}
Tip: More the calls, slower the execution
kanpur( ){
printf ( ”\n I am in Kanpur” ) ; bombay( ) ;
}
main( ){
printf ( ”\n I am in main” ) ;
bombay( ) ; kanpur( ) ;
}
bombay( ){
printf ( ”\n I am in Bombay” ) ;
kanpur( ) ;} Tip: Any function can call
any other function
main( ){
printf ( ”\n I am in main” ) ;
main( ) ;
}
Local Call - Recursive Function
Process - Recursion
Two types of functions• Library functions
• User defined functions
Formals – Actuals
Parameters – Arguments
names need not be same
type, order and number must be the
same
main( )
{
int a = 10, b = 20, c = 30 ;
calsum ( ) ;
printf ( ”%d”, s ) ;
}
calsum( )
{
int a, b, c, s ;
}
int s ;
printf ( ”%d”, s ) ;
s = a + b + c ;
Garbage
Garbage
main( )
{
int a = 10, b = 20, c = 30 ; int s ;
calsum ( ) ;
printf ( ”%d”, s ) ;
}
calsum ( )
{
int s ;
}
printf ( ”%d”, s ) ;
s = x + y + z ;
a, b, c
int x, int y, int z
60
Garbage
Formal Arguments
ActualArguments
Void main( )
{
int a = 10, b = 20, c = 30, s ;
calsum ( a, b, c ) ;
}
Int calsum ( int x, int y, int z )
{
int ss ;
ss = x + y + z ;
return ( ss ) ;
}
s = calsum ( a, b, c ) ;
printf ( ”%d”, s ) ;60
return ( ss ) ;
return ( 60 ) ;
return ( x + y + z ) ;
Return control and value
return ; Returns only
control
calsum ( a, 25, d ) ;
calsum ( 10 + 2, 25 % 3, d ) ;
calsum ( a, calsum ( 25, 10, 4 ), d ) ;
d = calsum ( a, 25, d ) * calsum ( a, 25, d ) + 23 ;
calsum ( int x, int y, int z )
{
int ss ;
ss = x + y + z ;
return ( ss ) ;
}
Nested calls are legal.
Call within an expression are legal.
main( )
{
int a = 10, b = 20, c = 30 ;
printf ( ”%d%d”, s, p ) ;
}
sumprod ( )int x, int y, int z
ss = x + y + z ;
pp = x * y * z ;
sumprod ( a, b, c ) ; s, p = sumprod ( a, b, c ) ;
{
int ss, pp ;
return ( ss, pp ) ;
}
int s, p ;
A function can return only
1 value at a time
main( )
{
int a = 10, b = 20, c = 30 ;
int s, p ;
s = sumprod ( a, b, c ) ;
p = sumprod ( a, b, c ) ;
printf ( ”%d%d”, s, p ) ;
}
sumprod ( int x, int y, int z )
{
ss = x + y + z ;
pp = x * y * z ;
return ( ss ) ;
return ( pp ) ;
}
int ss, pp ;
60 60
Redundant
main( )
{
int a = 10, b = 20, c = 30 ;int s, p ;
s = sumprod ( a, b, c ) ;
p = sumprod ( a, b, c ) ;
printf ( ”%d%d”, s, p ) ;
}
, 1
, 2
sumprod ( int x, int y, int z, )
{
ss = x + y + z ; pp = x * y * z ;
int ss, pp ;
}
int code
if ( code == 1 )
return ( ss ) ;
else
return ( pp ) ;
Call by Value Original is not modified main() {
• int x = 3;
• func(x);
• printf(“%d”, x); } int func(int x) {
• x++;
• return x; } C‟s calling convention is right to left
• int a = 1;
• printf(“%d %d %d\n”, a, ++a, a++);
• 3 3 1 !!
Return is optionalAny number of return statements are
allowedReturn need not be the last statement return expression; return;
• return value is garbage return (2);Function need not return a valueCaller may ignore return valueOnly one value at a time can be returnedCompiler only gives warnings
Returning a non-integer value
Call by value / Call by reference
Recursion
square ( 2.0 ) ;
main( )
{
a = square ( 2.0 ) ;
b = square ( 2.5 ) ;
c = square ( 1.5 ) ;
printf ( ” %f %f %f ”, a, b, c, ) ;
}
square ( )float x
{
float y ;
y = x * x ;
printf ( ” %f ”, y ) ;
return ( y ) ;
}
FunctionPrototype
4.0 6.0 2.0
float a, b, c ; float square ( float ) ;
4.0
6.25
2.25
float square ( float x )
scope is local to the function
x defined in main() is not available in
func() and vice versa
Local
Global
Topics
Scope of variable
Automatic variables
External variables
Scopes and longevity of above types of
variables.
10
2
1. Scope: the scope of a variable determines
over what part(s) of the program a
variable is actually available for
use(active).
2. Local(internal) variables: are those which
are declared within a particular function.
3. Global(external) variables: are those
which are declared outside any function.
10
3
Are declare inside a function in which they are to be utilized.
Are declared using a keyword auto.eg. auto int number;
Are created when the function is called and destroyed automatically.
This variable are therefore private(local) to the function in which they are declared.
Variables declared inside a function without storage class specification is, by default, an automatic variable.
If automatic variables are not initialized they will contain garbage.
10
4
int main(){ int m=1000;function2();printf(“%d\n”,m);
}function1(){int m = 10;printf(“%d\n”,m);
}function2(){ int m = 100;
function1();printf(“%d\n”,m);
}
10
5
Output
10
100
1000
These variables are declared outside any function.
These variables are active and alive throughout the entire program.
Also known as global variables and default value is zero.
Unlike local variables they are accessed by any function in the program.
In case local variable and global variable have the same name, the local variable will have precedence over the global one.
Sometimes the keyword extern used to declare these variable.
10
6
int number;float length=7.5;main(){ number = 19; length=7.5;
}funtion1(){number = 19; length=7.5;
}funtion1(){number = 19; length=7.5;
}
10
7
int count;
main()
{count=10;
. . .
. . .
}
funtion()
{int count=0;
. . .
. . .
count=count+1;
}
The variable number and
length are available for use in
all three function
When the function references the
variable count, it will be referencing
only its local variable, not the global
one.
int x;int main(){x=10;printf(“x=%d\n”,x);printf(“x=%d\n”,fun1());printf(“x=%d\n”,fun2());printf(“x=%d\n”,fun3());}int fun1(){ x=x+10;return(x);
}int fun2(){ int xx=1;return(x);
}
10
8
int fun3(){ x=x+10;return(x);
}
Once a variable has been declared
global any function can use it and
change its value. The subsequent
functions can then reference only
that new value.
Output
x=10
x=20
x=1
x=30
int main(){
y=5;. . .. . .
}int y;
func1(){y=y+1}
10
9
• As far as main is concerned, y is not
defined. So compiler will issue an error
message.
• There are two way out at this point
1. Define y before main.
2. Declare y with the storage class extern
in main before using it.
int main(){extern int y;. . .. . .
}func1(){extern int y;. . .. . .}int y;
11
0
Note that extern declaration
does not allocate storage
space for variables
11
1
11
2
11
3
11
4
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
main()
{
auto int result;
int value1, value2, value3;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, result);
}
int add_numbers( void )
{
auto int result;
int value1, value2, value3;
result = value1 + value2 + value3;
return result;
}
11
5
Static Variables and constants in C
main( ){
printf ( ”Enter Marks” ) ;
scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;per = ( m1 + m2 + m3 ) / 3 ;printf ( ”%d”, per ) ;
}
int m1, m2, m3, per ;
for ( i = 1 ; i <= 10 ; i++ ){
}
int i ;
printf ( ”%d”, per ) ;
Use 10 variables each holding 1 value
Use 1 variable holding all 10 values
Array
What is an Array?
Array is a variable capable of
holding more than 1 value at a time
32, 62, 65, 42, 48, 70, 80, 86, 92, 68{ }per =
peri per perii
per ( i ) per [ i ]
Screen
per3per1 per6
per10
main( ){
printf ( ”Enter Marks” ) ;
scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;per[ i ] = ( m1 + m2 + m3 ) / 3 ;
}
int m1, m2, m3, per[ 10 ] ;
for ( i = 1 ; i <= 10 ; i++ ){
}
int i ;
printf ( ”%d”, per[ i ] ) ;
for ( i = 1 ; i <= 10 ; i++ )
0 9
0 9
Array?A
Screen
0
0
int i = 2 ;main( ){
int a[ ] = { 7, 6, 11, -2, 26 } ;
optional
int b[ 10 ] ; compulsory
int c[ ] = { 16, 13, -8, -7, 25 } ;10
printf ( ”%d%d”, sizeof ( a ), sizeof ( b ) ) ;
printf ( ”%d%d”, a[ 0 ], b[ 0 ] ) ;
scanf ( ”%d%d%d”, ) ;&c[ 7 ], &c[ 8 ], &c[ 9 ]
c[ 5 ] = 3 + 7 % 2 ;
c[ 6 ] = c[ 1 ] + c[ 3 ] / 16 ;
}
10 20
int i ;i = 2 ;
7 G
Arrays can be initialized
Array elements can be scanned
Array elements can be calculated
Arithmetic on array elements is allowed
Then how are they different?
main( ){
int i = 3, j = 20, k = -5, l = 7, m = 11 ;
int a[ ] = { 3, 20, -5, 7, 11 } ; int ii ;
printf ( ”%u %u %u %u %u”, &i, &j, &k, &l, &m ) ;
for ( ii = 0 ; ii <= 4 ; ii++ )
printf ( ”%u”, &a[ ii ] ) ;
502 504 506 508 510
3 20 -5 7 11
502 504 506 508 510
a[0] a[1] a[2] a[3] a[4]
100 }
400 500 700 600
3
i
100
20
j
400
k
-5500
7
l
700
11
m
600
a[ ] = { 2, 1.4, ’A’, 6 } ;
- Adjacency
- Similarity
int
main( ){
int a[ ] = { 3, 60, -5, 7, 11 } ;int i ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( ”%d”, a [ i ] ) ;
}
a[ i ] = a[ i ] * 2 ;
for ( i = 0 ; i <= 4 ; i++ )
0
0
Subscript outof range
3 60 -5 7 11500 502 504 506 508
a[0] a[1] a[2] a[3] a[4] a[5] a[6]
510 512
Arrays are variables capable of storingmultiple values
Array elements are stored in adjacentmemory locations
Checking the bounds of an array is programmer’s responsibility
main( ){
int a[ ] = { 7, 9, 16, -2, 8 } ;
int i ;
display ( a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ] ) ;
for ( i = 0 ; i <= 4 ; i++ )
display1 ( a[ i ] ) ;
}
display ( ){
printf ( ”%d %d %d %d %d”, i, j, k, l, m ) ;
}
display1 (int n) {
printf ( ”%d”, n ) ;
}
int i, int j, int k, int l, int m
Passing Array Elements to Functions
Whichis good?
printf ( ”%d”, a[ ][ ] ) ;
main( ){
int a[ ][ ] = {
{ 2, 6, 1, 8, 4 }
{ 1, 2, 5, 6, 8 }
{ 7, 9, 8, 7, 21 }
{ 4, 5, 6, 8, 10 }
} ;
int i, j ;
2 4
printf ( ”%d %d”, sizeof ( a ), a ) ;
for ( i = 0 ; i <= 3 ; i++ )
{
for ( j = 0 ; j <= 4 ; j++ )
printf ( ”%d”, a [ i ][ j ] ) ;
printf ( ”\n” ) ;}
}
5
int b[ ][1][2][3]
optional
compulsory
21
40 4080
optional
,
,
,
compulsory
compulsory
optional
Exception
int a[ ][ 4 ] = {7, 2, 6, 1, 9, 3, 4, 5, 10, 12, 16, 18
} ; }
Row Major
502 504 506 508 510 512 514 516 518 520 522 524
main( ){
9 3 4 5 10 12 16 181627
Representation of 2-D Arrays in Memory
main( ){ int a[ ][ ] = {
7, 2, 6, 13, 5, 4, 86, 2, 9, 50 1, 2, 3, 8
} ;
,,,
big = a[ 0 ][ 0 ] ;
for ( i = 0 ; i <= 3 ; i++ )
for ( j = 0 ; j <= 3 ; j++ ){
{if ( a[ i ][ j ] > big )
big = a[ i ][ j ] ;{
r = i ; c = j ;}
}}
printf ( ”%d ”, big ) ; printf ( ”%d %d ”, r, c ) ; }
4
r = 0 ; c = 0 ;
int i, j, big ; int r, c ;
Matrices - Addition, Multiplication,
Chess
Q
Q
Q
Q
Q
Q
Q8 8Board
Determinant,Transpose, Inverse etc .
main( )
{
char name[ ] = { ‟S‟, ‟a‟, ‟n‟, ‟j‟, ‟a‟, ‟y‟, „\0‟ } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
printf ( ”%c”, name[ i ] ) ;
i = 0 ;
while ( name[ i ] ! = ‟\0‟ )
{
printf ( ”%c”, name[ i ] ) ;
i++ ;
}
}
name[ i++ ]
main( )
{
char name[ ] = { ‟S‟, ‟a‟, ‟n‟, ‟j‟, ‟a‟, ‟y‟, „\0‟ } ;
int i ;
printf ( ”%d%d”, ‟\0‟, ‟0‟ ) ;
0 48
i = 0 ;
while ( name[ i ] ! = 0 )
printf ( ”%c”, name[ i++ ] ) ;
}
i = 0 ;
while ( name[ i ] )
printf ( ”%c”, name[ i++ ] ) ;
Two More Ways
for ( i = 0 ; i <= 5 ; i++ )
while ( name[ i ] ! = ‟\0‟ )
while ( name[ i ] ! = 0 )
while ( name[ i ] )
printf ( ”%s”, name ) ;
Which Is Best?
char str1[ ] = { ‟S‟, ‟a‟, ‟n‟, ‟j‟, ‟a‟, ‟y‟, „\0‟ } ;
char str2[ ] = ”Sanjay” ;
printf ( ”%d%d”, sizeof ( str1 ), sizeof ( str2 ) ) ;
printf ( ”Enter name & surname” ) ;
scanf ( ”%s”, str3 ) ;
printf ( ”%s”, str3 ) ;
printf ( ”Enter name & surname” ) ;
printf ( ”%s”, str3 ) ;
gets ( str3 ) ;
}
char str3[ 15 ] ;
7 7
Rahul
Rahul Sood
Multiword Stringsmain( ){
Rahul Sood
Rahul Sood
puts ( str3 ) ;
3
3.0
‟3‟
”3”
Different
\0 Assumed
StringTerminator
char str1[ ] = ”Amol” ;
char str2[ ] = ”Sanjay” ;
printf ( ”%s%s%s”, str1, str2, str3 ) ;
gets ( str1 ) ;
gets ( str2 ) ;
gets ( str3 ) ;
char str3[ ] = ”Rahul” ;
Which Is Better?main( ){
puts ( str1 ) ;
puts ( str2 ) ;
puts ( str3 ) ;
scanf ( ”%s%s%s”, str1, str2, str3 ) ;
}
strlenstrcpystrcat
struprstrlwrtouppertolowerstrcmpputsgets
strncpy ( str1, str2, 5 ) ;strncat ( str1, str2, 6 ) ;strncmp ( str1, str2, 6 ) ;strncmpi ( str1, str2, 4 ) ;
strnicmp ( str1, str2, 4 ) ;
strchr ( ”Hello”, ‟e‟ ) ;
strstr ( ”I am a boy”, ”am” ) ;strsetstrnset. .. .. .
Standard Library Functions
Is there any error here?
f(int a, int b) {• int a;
• a=20;
• return a;
}
int main() {• int a = 10;
• void f();
• a=f();
• printf (“%d\n”, a);
• return 0;
}void f() {
• printf(“Hi”);
}
int main() {• int i=1;
• if(!i) printf(“Hi\n”);
• else { i=0;
printf(“Hello\n”);
main();
• }
• return 0;
}
int main() {• int fun (int);
• int i=fun(10);
• printf(“%d\n”, --i);
• return 0;
}
int fun (int i) {• return (i++);
}
int main() {• int k=10;
• k=func1(k=func1(k=func1(k)));
• printf(“k=%d\n”, k);
• return 0;
} int func1(int k) {
• k++;
• return (k);
}
int fun(); int i; int main() {
• while(i) { fun();
main();
• }
• printf(“Hello\n”);
• return 0; } int fun() {
• printf(“Hi”);
• return 0; }
int main() {• int i=10, j;
• j=f(i);
• printf(“%d\n”, j);
} int f (int j) {
• int k=3;
• j = j*k;
• return (j,k);
}
Every function must return a value – T or F?
Default return type of a function?Re declaration of a function is an error – T
or F?Re definition of a function is an error – T
or F?There should be only one return
statement in a function – T or F?Problem with TOO MANY recursive calls?
int main() {• int arr[2][] = {
{1,2,3,4,5},
{6,7,8,9,10}
• };
• return 0;
}
Is something wrong?
num[1] means the very first element of
array called num – T or F?
int num[2][4] can also be thought of as
two arrays of 4 elements each – T or F?
int main() {• int arr[1]={10};
• printf(“%d\n”, 0[arr]);
• return 0;
}
What‟s the output?
int main() {• int arr[]={2,3,4,1,6};
• printf(“%u %u %u\n”, arr, &arr[0], &arr);
• return 0;
}
What‟s the output if base address is
275676?
int main() {• int a[5] = (5,1,15,20,25}
• int i,j,m;
• i=++a[1];
• j=a[1]++;
• m=a[i++];
• printf(“%d %d %d\n”, i,j,m);
• return 0;
}
int main() {• char s[] = “abcdef ghi jkl”;
• printf(“%s\n”, &s[2];
• printf(“%s\n”, s);
• printf(“%s\n”, &s);
• printf(“%c\n”, s[2]);
• return 0;
}