Notes On C Language: From: Prof Saroj Kaushik CSE Dept, IIT Delhi
Notes On C Language: From: Prof Saroj Kaushik CSE Dept, IIT Delhi
case vn : sn ; break;
default : s optional
}
– If the value of exp is vj then sj is executed and
switch statement is exited using break
statement.
– Execution always starts from 1 to last.
Input/Output statement
/* reads single character and stores in
character variable x */
x = getchar();
/* prints single character stored in x*/
putchar(x);
/* the following functions are in standard file
named stdio.h */
scanf(control, v1, v2, ..);
printf(control, e1,e2,...);
• Control in input/output
control = "seq of format descriptor“
Format descriptor
Description Meaning
%d a decimal integer
%o a octal integer
%x a hexadecimal integer
%c a single character
%s a character string
%f a decimal number (float
or double)
\n skip to new line
Examples:
• printf("%4d%7.2f\n%c\n", x, y, z)
• printf(“%c %d %f”, ch, i, x);
• scanf("%4d%8.2f \n", &x, &y)
• scanf(“%c %d %f”, &ch, &i, &x);
– Here & represents memory addresses
Arrays
• Single dimensional Array
– Arrays in C are defined as:
int numbers[50];
– In C Array subscripts start at 0 and end
one less than the array size whereas in
other languages like fortran, pascal it
starts from 1.
– For example, in the above case valid
subscripts range from 0 to 49.
– Elements can be accessed in the
following ways:-
numbers[2] = 100; x = numbers[2];
• Multi-dimensional arrays can be
defined as follows:
int x[50][50]; // for two dimensions
• X is an array with 50 rows and 50
columns
• Elements can be accessed in the
following ways:
y=x[2][3];
• For further dimensions simply add
more [ ]:
int x[50][50][40][30]......[50];
Strings
• In C, Strings are defined as arrays of
characters.
– For example, the following defines a
string of 50 characters: char name[50];
• C has no string handling facilities built
in and so the following assignments
are illegal:
char fn[10],ln[10],fulln[20];
fn= "Arnold";
ln= "Schwarznegger";
fulln= "Mr"+fn +ln;
• However, there is a special library of
string handling routines <string.h>
which may be included in header file
and then various string operations can
be used.
• String is enclosed in “ “.
– Printf(“Well done”);’
• To print a string we use printf with a
special %s control character:
printf(``%s'',name);
– NOTE: We just need to give the name of the
string.
• In order to allow variable length
strings the 0 character is used to
indicate the end of a string.
• So if we have a following declaration
char name[50];
• Initialization can be done at the
declaration time as follows:
char name[50] = “DAVE”;
• The contents will look like:
String Handling Functions
• Include <string.h> as a header file. The
following functions are available for use.
• Concatenate two strings: strcat(s1, s2)
• Compare two strings : strcmp(s1, s2)
• Length of string : strlen(s)
• Copy one string over other: strcpy(s1, s2)
– Here contents of s2 are copied to s1
• Locating substring: strstr(s1,s2)
– Gives the position of s1 in s2
Structure in C
• A structure in C is a collection of items
of different types.
• The main use of structures is to
conveniently treat such collection as a
unit.
• For example:
struct employee
{ char name[50];
char sex;
float salary;
};
• The following declaration defines a
variable xyz of struct type.
struct empolyee xyz;
• Variables can also be declared
between } and ; of a struct
declaration, i.e.:
struct employee
{ char name[50];
char sex;
float salary;
} xyz;
• struct variable can be pre-initialized at
declaration:
struct employee
{ char name[50];
char sex;
float salary;
} xyz = {"john", ’m’, 20000.50};
• To access a member (or field) of a
struct, C provides dot (.) operator.
• For example,
– xyz . sex ; xyz . salary; xyz . name
User Defined Data Types
• Enumerated Types
– It contains a list of constants that can be
addressed in integer values.
• We can declare types as follows.
enum days {MONDAY, TUESDAY, ...,
SUNDAY};
• Variables of enumerated type are defined
as follows:
enum days week1, week2;
where week1 and week2 are variables
Possible uses of enumerated constants
• Enumerated constants can be assigned
to variable of that type
week1 = MONDAY;
• Conditional expression can be formed
If (week1 == week2) ….
if (week1 != TUESDAY) …
• Can be used in switch or for statement.
• Similar to arrays, first enumerated name
has index value 0.
– So MONDAY has value 0,
– TUESDAY value1, and so on.
• We can also override the 0 start value as
follows:
enum months {JAN = 1, FEB, MAR, ..., DEC};
– Here it is implied that FEB = 2 and so on
enum colors {RED, BLUE, GREEN=5, WHITE,
PINK=9};
– Here RED=1, BLUE=2, GREEN=5, WHITE=6,
PINK=9
#include <stdio.h>
main()
{
enum Color {RED=5, YELLOW, GREEN=4,
BLUE};
printf("RED = %d\n", RED);
printf("YELLOW = %d\n", YELLOW);
printf("GREEN = %d\n", GREEN);
printf("BLUE = %d\n", BLUE);
}
Output:
RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5
Type Definitions
• We can give a name to enum colors as COLOR
by using typedef as follows:
typedef enum colors COLOR;
COLOR x, y, z;
x = RED;
y = BLUE;
• Now, every time the compiler sees COLOR, it'll
know that you mean enum colors.
• We can also define user named data type for
even existing primitive types:
typedef int integer;
typedef bool boolean;
• typedef can also be used with structures to
creates a new type.
• Example:
typedef struct employee
{ char name[50];
char sex;
float salary;
} emp_type xyz ={"john", ’m’, 2000.50};
Output is: B
• In order that the program can keep track of
the type of union variable being used, it is
embedded in a structure and a variable
which flags the union type.
• For example:
typedef struct { int maxpassengers; } jet;
typedef struct { int liftcapacity;} helicopter;
typedef struct { int maxpayload; } cargoplane;
typedef union
{ jet j; helicopter h; cargoplane c; } aircraft;
typedef struct
{ aircrafttype kind; int speed;
aircraft description; } an_aircraft;
Function
• C provides functions which are again
similar in most languages.
• One difference is that C regards main()
as a function.
• The form of a C function is as follows:
type fun_name(parameter along with type)
{ local declarations;
body;
}
• type : is the type of value returned by the
function and can be basic type or user
defined.
• return statement is used in the body of a
function to pass the result back to the
calling program.
• Example: Write function to find the
average of two integers:
float findaverage(float a, float b)
{ float average;
average=(a+b)/2;
return(average);
}
• We would call the function as follows:
result=findaverage(6,23);
#include <stdio.h>
main()
{ int i, x;
int power (x, n); function declaration
for (i =0; i < 10; ++i)
{ x = power(2, i);
printf("%d%d\n", i, x); }
}
int power(int x, n) function definition
{ int i, p;
p = 1;
for (i =1; i <=n; i++) p = p*x;
return (p); }
void functions
• The void function provides a way of not
returning any value through function name
• Here return statement is not used:
void squares()
{ int i;
for (i=1;i<10;i++);
printf("%d\n",i*i);
}
• In the main function we call it as follows:
main( )
{ squares( ); }
Parameter Passing
• Default parameter passing is by value.
– The values of actual parameters are copied in
formal parameters.
– The change is not visible in the calling program.