C Programming: Conducted by Sarwar Morshed Senior Lecturer, CSE
C Programming: Conducted by Sarwar Morshed Senior Lecturer, CSE
Lecture 4
Conducted by
Sarwar Morshed
Senior Lecturer, CSE
2013-04-12
Structured Programming in C
Blocks
Blocks combine multiple statements into a single unit.
Can be used when a single statement is expected.
Creates a local scope (variables declared inside are local to the block).
Blocks can be nested.
int x=0;
{
int y=0; / both x and y visible /
}
/ only x visible /
2013-04-12
Structured Programming in C
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
2013-04-12
Structured Programming in C
Conditional blocks
if ... else..else if is used for conditional branching of
execution
if ( cond )
{
/ code executed if cond is true /
}
else
{
/ code executed if cond is false /
}
2013-04-12
Structured Programming in C
Conditional blocks
if ... else..else if is used for conditional branching of
execution
if ( cond ) {
/ code executed if cond is true /
}
else
{
/ code executed if cond is false /
}
2013-04-12
Structured Programming in C
Conditional blocks
switch..case is used to test multiple conditions (more efficient than if
else ladders).
2013-04-12
Structured Programming in C
Example
switch ( opt ) {
case A :
/ execute if opt == A /
break ;
case B :
case C :
/ execute if opt == B || opt == C /
default :
}
2013-04-12
Structured Programming in C
2013-04-12
Structured Programming in C
Iterative blocks
while loop tests condition before execution of
the block.
do..while loop tests condition after execution
of the block.
for loop provides initialization, testing and
iteration together.
2013-04-12
Structured Programming in C
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
2013-04-12
Structured Programming in C
10
break keyword
Sometimes want to terminate a loop early
break; exits innermost loop or switch statement to exit early
consider the modification of the do...while example
char c;
Do{
/* loop body */
Puts(keep going? (y/n) );
C= getchar();
If(c != y)
break;
/*other processing*/
} while (/*other conditions*/)
2013-04-12
Structured Programming in C
11
continue keyword
Use to skip an iteration
continue; skips rest of innermost looop body, jumping to loop
condition
Example:
# define min(a,b) ((a)<(b)?(a):b))
int gcd(int a, int b){
int i, ret=1, minval=min(a,b);
for(i=2;i<=minval;i++){
if(a%i) /* i not divisor of a*/
continue;
if(b%i==0) /*i is divisor of both a & b*/
ret = i;
}
}
2013-04-12
Structured Programming in C
12
goto
goto allows you to jump unconditionally to arbitrary part of your code (within the
same function).
the location is identified using a label.
a label is a named location in the code. It has the same form as a variable followed
by a :
start :
{
if ( cond )
goto outside ;
/ some code /
goto start ;
}
outside :
/ outside block /
2013-04-12
Structured Programming in C
13
Spaghetti code
Dijkstra. Go To Statement Considered Harmful.
Communications of the ACM 11(3),1968
Excess use of goto creates sphagetti code.
Using goto makes code harder to read and debug.
Any code that uses goto can be written without using one.
2013-04-12
Structured Programming in C
14
2013-04-12
Structured Programming in C
15
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
2013-04-12
Structured Programming in C
16
2013-04-12
Structured Programming in C
17
Example of putchar()
/* putchar example: printing the alphabet */
#include <stdio.h>
int main ()
{
char c;
for (c = 'A' ; c <= 'Z' ; c++)
putchar (c);
return 0;
}
This program writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to the standard
output.
2013-04-12
Structured Programming in C
18
Exmple of getchar()
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
A simple typewriter. Every sentence is echoed once ENTER has been pressed
until a dot (.) is included in Structured
the text.
2013-04-12
Programming in C
19
Standard output:formatted
int printf (char format[],arg1,arg2 ,...)
printf() can be used for formatted output.
It takes in a variable number of arguments.
It returns the number of characters printed.
The format can contain literal strings as well as
format specifiers (starts with %).
Examples:
printf ( "hello world\n" );
printf ( "%d\n" ,10); / format: %d (integer),argument:10 /
printf ( "Prices:%d and %d\n" ,10 ,20);
2013-04-12
Structured Programming in C
20
2013-04-12
Type
Meaning
Example
d,i
integer
x,X
integer(hex)
unsigned integer
character
string
float
double
e,E
foat(exp)
1e3,1.2E3,1E3
literal %
21
Arrays
Array: is a list of similar variables.
Declaration: data_type variablename[size];
int a[10];
double a[10];
char a[10];
Callsification of Array:
One dimensional array: int a[10];
Two dimensiona array: int a[10][5];
Three dimensional array is essentially an array of two-dimensional
arrays: int a[4][5][3];
Array elements start from 0 position.
Initialization of array:
int a[3] = {4, 2, 8};
c[0] c[1] c[2]
A
B
C
char c[3] = {A, B, C};
c Programming
2013-04-12
Structured
in C
22
Example
Get values into an array and print them
int main()
{
int a[5], i;
printf(Enter 5 integer values);
/*inserting array elements from key board*/
for(i=0; i<5;i++){
scanf(%d, &a[i]);
}
/*print the inserted values from array */
for(i=0; i<5;i++){
printf(%d , a[i]);
}
return 0;
}
2013-04-12
Structured Programming in C
23
24
2013-04-12
Structured Programming in C
25
Structured Programming in C
26
String Example
int main()
{
char str[80];
int i;
printf(Enter a string (less than 80));
gets(str);
for(i=0;str[i]!=\0;i++)
printf(%c,str[i]);
return 0;
}
2013-04-12
Structured Programming in C
27
character arrays
Comparing strings: the header file <string.h> provides the function
int strcmp(char s[],char t []) that compares two strings in
dictionary order (lower case letters come after capital case).
the function returns a value <0 if s comes before t
the function return a value 0 if s is the same as t
the function return a value >0 if s comes after t
strcmp is case sensitive
Examples
strcmp("A","a")/<0/
strcmp("IRONMAN","BATMAN")/>0/
strcmp("aA","aA")/==0/
strcmp("aA","a")/>0/
2013-04-12
Structured Programming in C
28
example
#include<string.h>
#include<stdio.h>
#define MAX_STRING_LENGTH 100
int main() {
/* this program reads word by word and increments a counter each time until
the string "exit" is entered */
char S[MAX_STRING_LENGTH];
int count; count = 0;
do {
printf("string:\t");
scanf("%s",S);
if (strcmp(S,"exit") != 0)
++count;
} while (strcmp(S,"exit") != 0);
printf("word count:\t%d\n", count);
}
2013-04-12
Structured Programming in C
29
Formatted input
int scanf(char format ,...) is the input analog of printf.
scanf reads characters from standard input, interpreting them
according to format specification
Similar to printf , scanf also takes variable number ofarguments.
The format specification is the same as that for printf
When multiple items are to be read, each item is assumed to be
separated by white space.
It returns the number of items read or EOF.
Important: scanf ignores white spaces.
Important: Arguments have to be address of variables (pointers).
2013-04-12
Structured Programming in C
30
2013-04-12
Structured Programming in C
31
String Functions
strlen(): to find length of the strings.
strlen(string); this will return 5.
strcmp(string1, string2): to compare the string. It returns 0
both strings are similar, returns less than 0, if string 1 is less
than string2, and returns greater than 0, if string1 is greater
than string2.
strcat(): to concatenate two strings. For example:
strcat(str1, str2);
will concatenate str2 to end of str1 if there is enough room.
strcpy(): to copy one string to another.
strcpy(str1, str2); this will copy str2 to str1.
2013-04-12
Structured Programming in C
32
Structured Programming in C
33
2013-04-12
Structured Programming in C
34
Storage class in c
The following are four types of storage class
available in C language.
2013-04-12
auto
register
extern
static
Structured Programming in C
35
extern keyword
Need to inform other source files about
functions/global variables
For functions: put function prototypes in a header
file
For variables: re-declare the global variable using the
extern keyword in header file
Extern informs compiler that the variable is defined
somewhere else
Enables access/modifying of global variable from
other sources.
2013-04-12
Structured Programming in C
36
Static variables
static variables are those variables whose life time remains
equal to the life time of the program.
static keyword has two meanings, depending on where the
static variable is declared
Outside a function, static variables/functions only visible
within that file, not globally (cannot be externed)
Inside a function, static variables:
are still local to that function
are initialized only during program initialization
do not get reinitialized with each function call
Structured Programming in C
37
Pointer
A pointer is a variable that holds the memory address of
another object.
Example: If a variable called p contains the address of another
variable called q, p is said to point to q. Therefore if the
address of q is 100 then adress of p would be 100.
Declaration: data_type *variable_name;
int *p;
# In C there are two pointer operators:
&: The & operator returns the address of the variable it
preceds.
*: The * operator returns the value stored at the address it
preceds.
2013-04-12
Structured Programming in C
38
Pointer
int main()
{
int *p,q;
q =199; /*assign q 199*/
p = &q; /*assign p the address of q*/
printf(%d, *p); /*displays qs value using pointer*/
return 0;
}
Pointer Restrictions:
1. Only four arithmetic operators can be applied with pointer: +,
++, -, --.
2. Add and subtract operation with pointer for integer values
only
2013-04-12
Structured Programming in C
39
Pointer
Example: if p contains the address 200, after following statement
p++;
Adress of p will be 202.
# Difference between these statements: *p++ ; and (*p)++;
Answer: 1st statement first increament p and then obtains the
value at the new location. In the second statement, the value
pointed at the location will be increamented.
Assume p is integer. If p address of p is 1000 and value assigned
this address is 7, then for the first statement address of p will be
1002 and value will be 7. In second case, address of p will be
same 100, but value will be 8.
2013-04-12
Structured Programming in C
40
2013-04-12
Structured Programming in C
41
2013-04-12
Structured Programming in C
42
2013-04-12
Structured Programming in C
43
2013-04-12
Structured Programming in C
44
Function prototyping
type function-name(type parameter-name1, type parametername2,...., type parameter-nameN);
Three atributes to be considered during function declaration:
Return type of the function
Number of parameter
Types of the parameters
2013-04-12
Structured Programming in C
45
Structured Programming in C
46
Variable scope
scope- the region in which a variable is valid
Many cases, it corresponds to block with variables
declaration
Variables declared outside of a function have global
scope
Variables declaraed within a function have local
scope
Function definition have also scope
2013-04-12
Structured Programming in C
47
An example
What is the scope of each variable in this example? int nmax = 20;
/ The main() function /
int main ( int argc , char argv) / entry point /
{
int a=0, b=1, c, n;
printf ( "%3d: %d\n" ,1 ,a );
printf ( "%3d: %d\n" ,2 ,b );
for (n =3; n<= nmax; n++) {
c=a+b; a=b; b=c;
printf ( "%3d: %d\n" ,n, c );
}
return 0; / success /
}
2013-04-12
Structured Programming in C
48
2013-04-12
Structured Programming in C
49
}
2013-04-12
Structured Programming in C
50
2013-04-12
Structured Programming in C
51
Recursive function
Recursion: Recursion is the process by which something is
defined in terms of itself. In computing, recursion means
when function can call itself.
Example:
Int main()
{
int fact, value;
printf(Enter an integer value);
scanf(%d, &value);
fact=factorial(value);
printf(factorial of this value is: %d, fact);
}
2013-04-12
Structured Programming in C
52
Recusive function
int factorial(int value)
{
int result;
result=value*factorial(value-1);
return result;
}
Another example:
int main()
{
recurse(0);
return 0;
}
2013-04-12
Structured Programming in C
53
void recurse(int i)
{
if(i<10){
recurse(i+1); /*recursive call*/
printf(%d,i);
}
}
Result: 9 8 7 6 5 4 3 2 1 0
2013-04-12
Structured Programming in C
54
Mutual Recursion
Mutual recursion occurs when one function calls another,
which in turn calls the first.
Example:
int main()
{
f1(30);
return 0;
}
void f1(int a)
{
if(a) f2(a-1);
printf(%d, a);
}
2013-04-12
Structured Programming in C
55
More functions
tolower() and touppe()
int main(){
char str[80]; int i;
printf(Enter a string: );
gets(str);
for(i=0;str[i];i++)
str[i]=toupper(str[i]);
printf(%s\n, str); /*uppercase string*/
for(i=0;str[i];i++)
str[i]=tolower(str[i]);
printf(%s\n, str); /*lower case string*/
return 0;
2013-04-12
Structured Programming in C
}
56
File
The C I/O system supplies a consistent interface to the
programmer, independent of the actual I/O device being
used. To accomplish this, C provides a level of abstraction
between the programmer and hardware. This abstraction is
called a stream. The actual device providing I/O is called a file.
Files are used to store datas in the secondary memory(eg:hard disk, floppy, flash disk etc).
There are various file operations that can be done in C like
Creating a file, deleting a file, renaming a file, opening a file to
read/write/append datas etc.
2013-04-12
Structured Programming in C
57
2013-04-12
Structured Programming in C
58
Structured Programming in C
59
2013-04-12
Structured Programming in C
60
Writing to a file in C
fprintf()
fprintf() is used to write datas to a file from
memory.
Syntax for fprintf()
fprintf(file pointer,control string,variables);
Example:fprintf(fp,%s,name);
2013-04-12
Structured Programming in C
61
2013-04-12
Structured Programming in C
62
Closing a file in C
2013-04-12
Structured Programming in C
63
2013-04-12
Structured Programming in C
64
Structured Programming in C
66
Structured Programming in C
67
68
2013-04-12
Structured Programming in C
69
Structured Programming in C
70
Fseek example
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Langauge", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program, this will create a file file.txt
with the following content. Initially program creates file and writes This is
tutorialspoint.com but later we reset the write pointer at 7th position
from the beginning and use puts() statement which over-write the file
with the following content:
2013-04-12 This is C ProgrammingStructured
Programming in C
72
Langauge
Structure
A structure is an aggregate data type that is composed of two or
more related variables called members. Each member of
structure can have its own type, which may differ from the
types of other members.
Defining structure: To define a structure, you must use the
struct statement. The struct statement defines a new data type,
with more than one member for your program. The format of
the struct statement is this:
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
2013-04-12
Structured Programming in C
73
Structure
The structure tag is optional and each member definition is a
normal variable definition, such as int i; or float f; or any other
valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more
structure variables but it is optional. Here is the way you would
declare the Book structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
2013-04-12
Structured Programming in C
74
2013-04-12
Structured Programming in C
75
Structured Programming in C
76
Structured Programming in C
77
Structured Programming in C
78
Structured Programming in C
79
2013-04-12
Structured Programming in C
80