C-Language (All Concepts)
C-Language (All Concepts)
Introduction to C
Data types in C
Variables
Type conversions
Standard input/output
Arithmetic, relational, logical operators
Header files and libraries
Loops and decisions
Scope of variables
Strings
Functions, call by value, call by reference
Arrays
Structures
Unions
Pointers
Files
History of C-Language
Why teach C?
Why use C?
C
is not "safe"
C-Language
Strengths:
1. Efficiency
2. Portability
3. Power
4. Flexibility
5. Standard library
6. Integration with UNIX
Weaknesses:
1. C programs can be error-prone
2. C programs can be difficult to understand
3. C programs can be difficult to modify
Structured Programming
Contd.
Compiler:
Processor:
Textual substitutions
Keywords
In Standard C, the keywords in Table 2.1 have special significance
to the compiler and therefore can not be used as identifiers.
Table 2.1 - Keywords
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
The Format of C
Variables
Program documentation
#Preprocessor directives
Global constants
Global variables
Function prototypes
int
main ()
{
Local variables
}
Function definitions
*/
source
helloworld.c
file
stdio.h
#include <stdio.h>
compiler
object file
helloworld.o
linker
helloworld
executable file
Variable Declaration
int b;
double x;
unsigned int a;
char c;
C is a typed language that means a variable
has a
name
type
C standard types
int, double, char, float, short, long, long
double
unsigned char, unsigned short, unsigned int,
unsigned long
Primitive Data-Types
integer data-types :
char, short, int, long, unsigned char, unsigned short,
floating point data-types :
float, double, long double
character data-type :
char
character constants in single quotes : a, \n
Primitive Data-Types
Type
char
short
Low
-128
-32768
High
127
32767
Digits of Bytes
Precision
1
2
int
2147483647
214748364
8
long
2147483647
214748364
8
float
double
3.4x10-38
1.7x10-308
3.4x1038
1.7x10308
7
15
4
8
long
3.4x10-4932
3.4x104932
19
10
Variable Definitions
A declaration introduces a variables name into a
program and specifies its type
A definition is a declaration which also sets
asides memory for that variable (which is usually
the case)
In C it is possible to initialize a variable at the
same
time it is defined, in the same way one assigns a
value
int a;
to
an already
double
x = 5.9; defined variable.
Examples
definitions:
char answerof= variable
n;
double y=x;
Constants
constants can be specified using the preprocessor
directive #define
example:
#define PI 3.14159
the preprocessor replaces the identifier PI by the
text
3.14159 throughout the program
the major drawback of #define is that the data type
of
the constant is not specified
the preprocessor merely replaces all occurences of
the
string PI with 3.14159
CONVENTION: reserve CAPITAL letters for constants
and use small caps for variables and functions
Comments
Type Conversions
Library Functions
Header Files
a header file contains the declaration of functions
you want to use in your code
the preprocessor directive #include takes care of
incorporating a header file into your source file
example:
#include <math.h>
#include myprog.h
the brackets <> indicate that the compiler first
searches
the standard include directory which contains the
standard C header files first
the quotation marks indicate that the compiler first
searches
for header files in the local directory
if you do not include the appropriate header file
you get an error message from the compiler
#include myprog.h
myprog.h
compiler
object file
myprog.o
library file
linker
executable file
myprog
libm.a
Input / Output
/*Program for print the different data types*/
#include <stdio.h>
int main()
{
int a;
double x;
char c;
printf(Enter integer:);
scanf(%d,&a);
printf(\nEnter double:);
scanf(%lf,&x);
printf(\nEnter character:);
scanf(%c,&c);
printf(\nThe value of a is %d, of x is %lf, of c is %c\n,a,x,c);
}
Input / Output
A stream is an abstraction that refers to a flow of data.
standard
output
device
stdout
printf(%d,a);
variable a
standard
input
device
stdin
scanf(%d,&a);
variable a
Input / Output
printf allows you to send output to standard out
(screen)
The special character \n represents carriage return
line feed
The symbol %d is a placeholder for an integer
variable in the format string
printf(the value of a is %d\n,a)
that will be replaced by the value of the variable a
when the printf statement is executed
Placeholders:
integer %d
long %ld
float %f
double %lf
char %c
string %s
Input / Output
Arithmetic Operators
multiplication, summation, subtraction, division
int i = 1/3; /* integer division result 0 */
float x = 1.0/3; /* floating point division result 0.3333 */
int j = 7 % 3; // modulo operator remainder of 7/3
prefix and postfix-increment operator ++
int i=3;
int j=7;
printf(%d,10 * i++); /* outputs 30, i has value 4 afterwards */
Printf(%d,10 * ++j); /* outputs 80, j has value 8 afterwards */
arithmetic assignment operators
float x=6.0;
x+=3.5;
is equivalent to
x=x+3.5;
Relational Operators
> greater
< less
>= greater or equal
<= less or equal
== equal, not to be confused with assignment
=
!= not equal
Relational Operators
a relational operator compares two values of primitive
in data types such as char, int, float
typical relationships are equal to, less than and
greater than
the result of a comparison is either true or false, where
0 is
false and any value different from 0 is true
C provides the following relational operators
<, >, ==, !=, <=, >=
example:
int x=44;
int y=12;
(x == y) /* false */
(x >= y) /* true */
Loops
For Loop
for ( i=0; i<15; i++ )
false
exit
For Loop
#include <stdio.h>
int main()
{
int a;
int i;
a=1;
for (i=0;i<10;i++)
{
printf(2 ^ %d = %d\n,i,a);
a*=2;
}
}
For Loop
For Loop
#include <stdio.h>
int main()
{
int number;
int i;
long fact;
fact=1;
printf(Enter number:);
scanf(%d,&number);
for (i=number; i>0; i--)
fact*=i;
printf(Factorial of %d is %ld\n,number,fact);
}
}
the body of the loop is executed as long as the test
statement is true (possibly zero times)
do
{
} while (a>b);
the body of the loop is executed and then repeated
as long as the test statement is true (at least once)
While Loop
test expression
while ( c != y )
{
}
test
expression
true
body of loop
false
exit
While Loop
#include <stdio.h>
int main()
{
int number;
int i;
long fact
fact=1;
printf(Enter number:);
scanf(%d,&number);
i=number;
while (i>0)
fact*=i--;
printf(Factorial of %d is %ld\n,number,fact);
}
While Loop
Do Loop
do
{ }
while ( c != y );
test expression
body of loop
test
expression
true
false
exit
Do - While Loop
#include <stdio.h>
int main()
{
i=number;
do
{
fact*=i--;
} while (i>0); /* do not forget the semicolon */
printf(Factorial of %d is %ld\n,number,fact);
}
Do Loop
If Else Statement
if ( x > 100)
{
}
else
{
test expression
test
expression
false
true
body of if
exit
body of else
If Else Statement
IfElse Statement
#include <stdio.h>
int main()
{
int a,b;
scanf(%d %d,&a,&b);
if (a>b)
printf(%d is larger than %d\n,a,b);
else
if (a==b)
printf(%d is equal to %d\n,a,b);
else
printf(%d is smaller than %d\n,a,b);
}
IfElse Statement
if (a>b)
{
}
else
{
}
the if part is executed if the test statement
is true, otherwise the else part is executed.
Logical Operators
logical and : &&
(x >= 5) && ( x <= 15) /* true if x in [5,15] */
logical or : ||
(x == 5) || ( x == 10) /* true if x=5 or x=10 */
logical negation : !
! (x == 5)
/* true if x is not equal to 5 */
x != 5
/* is equivalent */
conditional operator : ? :
<condition> ? <true expression> : < false
expression>
if (alpha < beta)
min = alpha;
else
min = beta;
Switch Statement
true
variable
equals
const 1
false
variable
equals
const 2
false
true
second case body
default body
exit
Switch Statement
break;
case <constant2>:
break;
default :
Switch Statement
char c;
printf(Enter your choice (a/b/c) : );
Scanf(%c,&c);
switch (c)
{
case a:
printf(You picked a!\n);
break;
case b:
printf(You picked a!\n);
break;
case c:
printf(You picked a!\n);
break;
default:
printf(You picked neither a,b,c !\n);
}
Scope of Variables
a block is a section of code delimited by a pair
of brackets { }
a declaration introduces a variable into a scope
( a specific part of program text)
the scope of a variable is the block within which
the variable is declared
a variable declared outside a function is global.
a declaration of a variable in an inner block can
hide
a declaration in an enclosing block or a global
variable
Scope of Variables
int i;
/* global variable */
visibility of outer i
lifetime of outer i
int main()
{
int i=3; /* local variable */
{
int j=5; /* local variable */
int i=7; /* local i hides outer i */
printf(%d\n i); /* outputs 7 */
} /* end of scope of j and inner i */
printf(%d\n i); /* outputs 3 */
} /* end of scope of outer i */
Characters
Type char
Characters are small integers (0255)
Character constants are integers
that denote corresponding
characters
'0','1','A','B','a','b','\n'
ASCII code maps characters to
integers
ASCII Code
0
48
49
50
51
52
53
54
55
56
57
65
66
67
68
69
70
71
72
73
74
97
98
99
100
101
102
103
104
105
106
NULL
(\0)
BEL
(\g)
TAB
(\t)
NEWLINE
(\n)
SPACE
10
32
Strings
String
is collection of Characters
(or ) group of elements.
Character
Example
char arr[4] = hi;
[0]
[1]
[2]
NU
LL
[3]
Strings
Two interpretations
Arrays whose elements are characters
Pointers pointing to characters
/* size? */
String Initialization
Initialization
char m[9] = I like C;
char m[ ] = I like C;
char m[] = { I, , l, i, k, e, ,C };
l i k e
C \0
m[8]
String Initialization
char s[30] = "c programming "; // ok, preferred
char s[30] = {"c programming "}; // ok, redundant
// illegal
// illegal
e \0
Null character
String Assignment
Make sure that you have
char s[5]="SIIT";
enough memory space to
char dept[5], *d=dept;
char name[20];
assign the string, otherwis
name = Peter Pan";
e some chars will be lost.
strcpy(name,Peter Pan");
strcpy(dept,"IT");
printf("%s %s %s\n",d,s,dept);
d = strcpy(s,"EE");
printf("%s %s %s %s\n",name,d,s,dept);
char c1[30], c2[30]=This is new c1 string;
char s[30] = "c programming ";
char str1[30];
char *str;
strcpy(c1, c2);
str = strcat(s,"is great!!");
str1 = strcat(s,"is great!!");
In-Class Example
void main()
{ char first[100], last[100];
int i;
strcpy(first,"Peter");
sprintf(last, "Pan");
printf("my name is %s, %s\n", last, first);
for (i=0; i<5; i++)
printf("%s \n",last);
getch();
}
Functions
a function groups a number of program statements
into a unit and gives it a name
the function can be invoked from other parts of the
program
dividing a program into functions is one way to
structure
your program (structured programming)
a function declaration specifies the name of the
function
the type of the value returned and the number and
type of arguments that must be supplied in a call of
the function
a function definition contains the body of the function
typically function declarations take place in header
files (.h)
What is a function?
An example function
Prototype the function
Call the function
function header
The function itself
number= 4
answer= 1
count= 4
enter while loop
answer= 1*4=4
count=3
enter while loop
answer=4*3= 12
count=2
enter while loop
answer=12*2= 24
count= 1
enter while loop
answer= 24*1= 24
count= 0
enter while loop
answer= 24*0= 0
Functions
int fac(int n); /* function declaration */
int x=7;
printf(fac(%d)=%d\n,x, fac(x)); /* call function fac()*/
int fac(int n) /* function definition */
{
int i;
int result=1;
for (i=1; i<=n; i++)
result*=i;
return result; /* exits function and returns value */
}
Functions
int pow(int a, int b); /* function declaration */
int a=3;
Int b=4;
printf(%d ^ %d =%d\n,a,b,pow(a,b)); /* call function fac()*/
int pow(int a, int b) /* function definition */
{
int result=1;
int i;
for (i=1; i<=b; i++)
result*=a;
return result; /* exits function and returns value */
}
POINTERS
POINTERS
A pointer is an address of a storage
location
By convention, zero represents the "null"
pointer
A pointer is a number, and must itself be
stored
POINTERS
Pointers
Pointers
Pointers
When is * used?
POINTER VARIABLES
A pointer variable is a variable that holds address
values
Each data type has its own pointer variable, pointer
to int, pointer to double, pointer to char,
C uses the address-of operator & to get the address
of an variable
C uses the indirection or contents-of operator * to
access the value of the variable pointed by
int i=17;
int* ptr; /* defines a pointer variable for integer variables */
ptr= &i; /* assign the address of i to pointer */
printf(the value of i can be printed as %d or %d\n, *ptr, i);
printf(the address of i is %d\n, ptr);
Pointer Variables
int i;
int *ptr;
ptr=&i;
0x1054
f
o
s
s
f
re
o
d
s
t
ad
en
t
n
co
printf(value of i = %d\n,*ptr);
17
Pointer Variables
int v; // defines variable v of type int
int w; // defines variable w of type int
int *p; // defines variable p of type pointer to int
p=&v; // assigns address of v to pointer p
v=3; // assigns value 3 to v
*p=7; // assigns value 7 to v
p=&w; // assigns address of w to pointer p
*p=12; // assigns value 12 to w
Passby-Value
Pass-by-Reference
void swap( double* ptr1, double* ptr2)
{
double tmp=*ptr1;
*ptr1=*ptr2; /* de-referencing pointer */
*ptr2=tmp;
}
int main()
{
double a=3.0;
double b=5.0
swap(&a, &b); /* call by reference using the addresses of a
and b */
printf(a=%lf, b=%lf\n,a,b);
}
main()
{
int n,factorial;
printf(enter a number);
scanf(%d,&n);
factcompute(n,&factorial);
printf(the factorial of %d,n,factorial);
}
factcompute(a,b)
int a,*b;
{
int m; *b=1;
for(m=1;m<=a;m++)
*b=*b*m;
}
Arrays
The
Arrays
int poweroftwo[10]; /*array definition */
int poweroftwo[0]=1; /* first element has index number 0 */
int i;
for (i=1;i<10,i++)
poweroftwo[i]=poweroftwo[i-1]*2;
for (i=0;i<10,i++)
printf(2 ^ %d = %d\n,i,poweroftwo[i]);
Arrays
double avg(int sz, double array[]); /* function definition*/
double x[5]={1.2, 2.5, 1.7, 4.2, 3.9} /* initialize array */
printf(average is %lf\n,avg(5,x));
double avg(int sz, double array[])
{
int i;
double sum;
for (i=0; i<sz; i++)
sum+=array[i];
return sum/sz;
}
Multi-Dimensional Arrays
#define ROWS 5
#define COLS 6
double matrix[ROWS][COLS];
double a[COLS];
double b[ROWS];
int i,j;
for(i=0;i<ROWS,i++)
{
b[i]=0.0;
for(j=0;j<COLS;j++)
b[i]+=matrix[i][j]*a[j];
}
#include<stdio.h>
#define MAXSIZE 100
main()
{
int n,I,max=0,elements[MAXSIZE];
printf(enter the no of elements);
scanf(%d,&n);
for(i=0, i<n, i++)
{
printf(enter value for element %d:,i);
scanf(%d,&elements);
}
for(i=0;i<n;i++)
{
if(max<elements[i])
max=elements[i];
}
printf(the maximum is %d,max);
}
Arrays in Pointers
#include <strings.h>
char lastname[256]=Hansen;
char firstname[256]=Ole;
char fullname[512];
strcpy(fullname,firstname);
strcat(fullname, );
strcat(fullname,lastname);
printf(full name is %s\n,fullname);
Structures
C Structures
struct card {
int face;
char suit[20];
};
struct card aCard, deck[52], *cardPtr;
Structures
Structures
are collections of
variables of different types, as in
the following example.
Structure
Definition
struct abc
{
int a;
long b;
char c;
}
MyStruct;
Structure
Type
Name
variable
declaration
Struct mydate
{
int yyyy;
int mmdd;
};
main()
{
struct mydate date1,date2;
int month1,month2;
char *months[]={ ,jan,feb,mar,.dec};
pf(enter first date(mmdd)); sf(%d,&date1.mmdd);
pf(enter second date(mmdd)); sf(%d,&date2.mmdd);
month1-date1.mmdd/100;month2=date2.mmdd/100;//take
month alone
pf(firstt month is %s,months[month1];
pf(second month is %s,months[month2]);
}
Struct currency
{ int rupees;
int paise;
};
main()
{ struct currency mycurr={123,25};
showit(&mycurr);
}
showit(struct currency *myptr)
{
pf(rupees %d,%d,myptrrupees,myptrpaise);
}
Unions
Unions
Unions
struct marks
{
int sub1; int sub2;
int sub3; int total; };
main()
{
int i;
static struct marks student[3]={ {56,45,65},
{59,55,75},45,65,75}};
static struct marks total;
for(i=0;i<=2;i++) {
student[i].total=student[i].sub1+student[i].sub2+student[i].sub3;
total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub2+student[i].sub2;
total.sub3=total.sub3+student[i].sub3;
}
Contd..
printf(STUDENT TOTAL);
for(i=0;i<=2;i++)
printf(student[%d] %d,i+1,student[i].total);
printf(SUBJECT
TOTAL);
printf(%s%d%s%d%s%d,
subject 1, total.sub1,
subject 2, total.sub2,
subject 3, total.sub3);
printf(Grand total=%d,total.total);
}
File Input In C
The C type, FILE allows for a consistent approach to input
regardless of the actual physical device
Default: stdin
stre
am
FILE
stream
C program
File Output In C
Similar to file input, the C type FILE allows for a consistent
approach to output regardless of the actual physical device
Default: stdout
str
ea
m
stream
am
e
r
t
s
FILE
C program
Format:
Example:
FILE *fp;
Opening Files
Format:
FILE * fopen (const char * filename, const char
* mode);
Example:
fp = fopen (data, r);
fp = fopen (/home/profs/tamj/data, r);
Error conditions
File does not exist.
Insufficient permissions to open the file.
Filename
Must reside in the same directory as C program being run
Alternatively you can include the path to the file
Mode
r
w
a
r+
w+
Closing Files
Example:
Example:
char arr[8];
fscanf (fp, %s, chunk);
Similar
#include
<stdio.h>
#include <stdlib.h>
int const LENGTH = 80;
main ()
{
FILE *fp_in, *fp_out ;
char arr[LENGTH];
char fn_in [LENGTH];
char fn_out [LENGTH];
printf("Enter name of input file: ");
scanf("%s", fn_in);
printf("Enter name of output file: ");
scanf("%s", fn_out);
while (feof(fp_in) == 0)
{
// Using fscanf it stops scanning at whitespace
fscanf(fp_in, "%s", arr);
fprintf(fp_out, "%s-", arr);
}
return(0);
}
(feof(fp_in) == 0)
<stdio.h>
#include <stdlib.h>
int
#include<stdio.h>
main()
{
char *filename;
FILE *fp1,*fp2;
int i, number;
fp1=fopen(TEST,w);
for(i=10;i<=100;i+=10){
putw(I,fp1);
fclose(fp1);
printf( Input File Name);
open_file;
scanf(%s,filename);
if((fp2=fopen(filename,r))==NULL){
printf(Cannot open the file);
printf(Type filenme again)
goto open_file;
}
else
for(i=1;i<=20;i++)
{
number=getw(fp2);
if(feof(fp2))
{
printf(Ran out of data);
break;
}
else
printf(%d,number);
}
fclose(fp2);
RECURSION
It is the process of calling of a function by itself. The
function which calls itself is known as recursive
function.
EXAMPLE: TO CALCUALTE FACTORIAL OF A NUMBER
int factorial(int);
void main()
{
int num,f;
printf(enter number whose factorial is to
be calculated);
scanf(%d,&num);
f=factorial(num);
printf(%d,f);
}
Contd
int factorial(int x)
{
if(x==1)
return 1;
else
return x*factorial(x-1);
}
THANX