SlideShare a Scribd company logo
1 of 30
Download to read offline
Learn
Programming
with
C Language
Compiled and Modified by:
Mark John Perez - Lado
Information System Enthusiast
Gathering Data
Designing
Testing
Page2
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
1. Introduction to C Language
1.1 Introduction
The C programming language is a general-purpose, high – level language (generally
denoted as structured language). C programming language was at first developed by
Dennis M. Ritchie at At&T Bell Labs.
C is one of the most commonly used programming languages. It is simple and efficient
therefore it becomes best among all. It is used in all extents of application, mainly in
the software development.
Many software's & applications as well as the compilers for the other programming
languages are written in C also Operating Systems like Unix, DOS and windows are
written in C.
C has many powers, it is simple, stretchy and portable, and it can control system
hardware easily. It is also one of the few languages to have an international standard,
ANSI C.
1.2 Advantages of C
1. Fast, Powerful & efficient
2. Easy to learn.
3. It is portable
4. ''Mid-level'' Language
5. Widely accepted language
6. Supports modular programming style
7. Useful for all applications
8. C is the native language of UNIX
9. Easy to connect with system devices/assembly
2. An Example of C program
2.1 Structure of program
/* This program prints Hello World on screen */
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf(''Hello Worldn'');
getch();
}
Page3
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
1 . /* This program ... */
The symbols/* and*/ used for comment. This Comments to provide useful information
about program to humans who use it.
2. #include<stdio.h>
Is the header file for standard input and output. This is useful for getting the input
from the user(Keyboard) and output result text to the monitor(Screen)
3. #include <conio.h>
has the function getch(), clrscr() and etc.
4. void main()
Is a main function in C language. Void means nothing return any value, this function is
used to execute the program. Without main() the program can compile but cannot run.
5. clrscr();
This function is used to clear the output screen.
6. { }
Braces surround the body of the function, which may have one or more
instructions/statements
7. printf()
It is a library function that is used to print data on the user screen.
8. ''Hello Worldn''
Is a string that will be displayed on user screen.
n is the newline character.
; a semicolon ends a statement.
9. getch();
It reads character from keyboard.
C is case sensitive language, so the names of the functions must be typed in lower case
as above. We can use white spaces, tabs & new line characters to make our code easy
to read.
Page4
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
3. Variables and Operators
3.1 Variables
3.1.1 Variable Declaration
Usually Variables are declared before use either at the first of the block of code after
the opening { and before any other statements or outside a function.
--------------------------
int a,b; /* global variables */
main()
{
float a; /* local variables */
}
--------------------------
Local variables can only be accessed within that function only whereas Global
variables can access in whole program.
3.1.2 Variable Types
There are many 'built-in' data types in C.
1. short int -128 to 127 (1 byte)
2. unsigned short int 0 to 255 (1 byte)
3. char 0 to 255 or -128 to +127 (1 byte)
4. unsigned char 0 to 255 (1 byte)
5. signed char -128 to 127 (1 byte)
6. int -32,768 to +32,767 (2 bytes)
7. unsigned int 0 to +65,535 (2 bytes)
8. long int -2,147,483,648 to +2,147,483,647 (4 bytes)
9. unsigned long int 0 to 4,294,967,295 (4 bytes)
10. float single precision floating point (4 bytes)
11. double double precision floating point (8 bytes)
12. long double extended precision floating point (10 bytes)
Page5
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
3.1.3 Variable Names
We can use any combination of letters and numbers for Variable and function names
but it must start with a letter.
We can use Underscore (_) as a letter in variable name and can begin with an
underscore. But identifiers beginning with an underscore are reserved, and identifiers
beginning with an underscore followed by a lower case letter are reserved for file
scope identifiers. Therefore using underscore as starting letter is not desirable.
Akki and akki are different identifiers because upper and lower case letters are treated
as different identifiers.
3.2 Operators
An operator is a symbol. Compiler identifies Operator and performs specific
mathematical or logical operation.
C provides following operators:
1. Arithmetic Operators
2. Increment and Decrement Operators
3. Relational Operators
4. Logical Operators
5. Cast Operators
6. Bitwise Operators
7. Assignment Operators
3.2.1 Arithmetic Operators
* - multiplication
/ - division
% - remainder after division (modulo arithmetic)
+ - addition
- - subtraction and unary minus
3.2.2 Increment and Decrement Operators
Increment and decrement operators are used to add or subtract 1 from the current
value of oprand.
++ - increment
-- - decrement
Page6
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
Increment and Decrement operators can be prefix of postfix. In the prefix style the
value of oprand is changed before the result of expression and in the postfix style the
variable is modified after result.
For example.
a = 9;
b = a++ + 5; /* a=10 b=14 */
a = 3;
b = ++a + 6; /* a=10 b=15 */
3.2.3 Relational Operators
== - equal.
!= - Not equal.
> < - Greater than/less than
>= - greater than or equal to
<= - less than or equal to
3.2.4 Logical Operators
&& Called Logical AND operator. If both the operands are non-zero, then condition
becomes true.
|| Called Logical OR Operator. If any of the two operands are non-zero, then condition
becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true, then Logical NOT operator will make false.
3.2.5 Cast Operators
Cast operators are used to convert a value from one to another type.
(float) sum; converts type to float
(int) fred; converts type to int
Page7
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
3.2.6 Bitwise Operators
Bitwise operators performs operation on actual bits present in each byte of a variable.
Each byte contain 8 bits, each bit can store the value 0 or 1.
~ - one's complement
& - bitwise AND
^ - bitwise XOR
| - bitwise OR
<< - left shift (binary multiply by 2)
>> - right shift (binary divide by 2)
3.2.7 Assignment Operators
= - assign
+= - assign with add
-= - assign with subtract
*= - assign with multiply
/= - assign with divide
%= - assign with remainder
>>= - assign with right shift
<<= - assign with left shift
&= - assign with bitwise AND
^= - assign with bitwise XOR
|= - assign with bitwise OR
For example,
a = a + 64; is same as
a += 64;
Page8
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
4. Input & Output
4.1 Formatted IO – printf and scanf
4.1.1 Formatted Output - printf
It takes text and values from within the program and sends it out onto the screen.
printf(''%f is your weightn'', w);
In the above program statement:
''%f is your weightn'' - is the control string
w - is the variable to be printed
%f - meaning that a floating point value is to be printed.
The number of conversion specifications and the number of variables following the
control string must be same, and that the conversion character is correct for the type of
parameter.
4.1.2 Formatted Input – scanf
scanf is used to get input from user and to store it in the specific variable(s).
scanf(''%d'', &x);
read a decimal integer from the keyboard and store the value in the memory address of
the variable x.
4.1.3 Character Escape Sequences
There are several character escape sequences which can be used in place of a character
constant or within a string.
a - alert (bell)
b - backspace
f - formfeed
n - newline
r - carriage return
t - tab
v - vertical tab
 - backslash
? - question mark
' - quote
'' - double quote
ooo - character specified as an octal number
xhh - character specified in hexadecimal
Page9
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
4.2 Character IO – getchar & putchar
getchar and putchar are used for the input or output only one character.
getchar() - It returns an int which is either EOF (indicating end-of-file) or the next
character in the standard input stream.
putchar(c) - Puts the character on the output stream.
int main()
{
int a;
a = getchar();
/* read and assign character to c */
putchar(a);
/* print c on the screen */
return 0;
}
5. Flow of control
5.1 Conditional branching – if
5.1.1 if statement
An if statement contains a Boolean expression and block of statements enclosed
within braces.
Structure of if statement:
if (boolean expression )
/* if expression is true */
statements... ; /* Execute statements */
If the Boolean expression is true then statement block is executed otherwise (if false)
program directly goes to next statement without executing statement block.
5.1.2 if...else statement
Page10
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
If statement block with else statement is known as as if…else statement. Else portion
is non-compulsory.
Structure of if...else:
if(condition)
{
statements...
}
else
{
statements...
}
If the condition is true, then compiler will execute the if block of statements, if false
then else block of statements will be executed.
We can use multiple if-else for one inside other this is called as Nested if-else.
5.2 Conditional Selection – switch
switch()
A switch statement is used instead of nested if...else statements. It is multiple branch
decision of statement of C. A switch statement tests a variable with list of values for
equivalence. Each value is called a case.
The case value must be a constant integer.
Structure of switch() statement :
switch (expression)
{
case value: statements...
case value: statements...
default : statements...
}
Individual case keyword and a semi-colon (:) is used for each constant. Switch tool is
used for skipping to particular case, after jumping to that case it will execute all
statements from cases beneath that case this is called as ''Fall Through''.
In the example below, for example, if the value 2 is entered, then the program will
print two one something else!
Page11
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
int main()
{
int i;
printf(''Enter an integer: '');
scanf(''%d'',&i); switch(i)
{
case 4: printf(''four ''); break;
case 3: printf(''three ''); break;
case 2: printf(''two '');
case 1: printf(''one '');
default: printf(''something else!'');
}
return 0;
}
To avoid fall through, the break statements are necessary to exit the switch. If value 4
is entered, then in case 4 it will just print four and ends the switch.
The default label is non-compulsory; it is used for cases that are not present.
5.3 Loops – while & for
while loop
The while loop calculates the expression before every loop. If the expression is true
then block of statements is executed, so it will not execute if the condition is initially
false. It needs the parenthesis like the if statement.
while ( expression )
/* while expression is true do following*/
statements... ;
Do While loop
This is equivalent to a while loop, but it have test condition at the end of the loop. The
Do while loop will always execute at least once.
do
statements ;
while ( expression );
/* while expression is true do...*/
Page12
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
For loop
This is very widely held loop.
For loops work like the corresponding while loop shown in the above example. The
first expression is treated as a statement and executed, then the second expression is
test or condition which is evaluated to see if the body of the loop should be executed.
The third expression is increment or decrement which is performed at the end of every
iteration/repetition of the loop.
for (expr1; expr2; expr3)
statements...;
In while loop it can happen that the statement will never execute. But in the do-while
loop, test condition is based at the end of loop therefore the block of statement will
always execute at least once. This is the main difference between the while and the do-
while loop.
For example, to execute a statement 5 times:
for (i = 0; i < 5; i++)
printf(''%dn'',i);
Another way of doing this is:
i = 5;
while (i--)
statements;
While using this method, make sure that value of i is greater than zero, or make the
test i -->0.
Page13
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
5.4 Local Jumps go to
We can jump to any statement inside the same function using goto. To spot the end of
point of the jump a label (tag) is used. goto statement is not to ideal to choose in any
programming language because it makes difficult to trace the flow of a program,
makes the program hard to understand, and to guess the output.
void any_function(void)
{
for( ... )
if (problem) goto error;
error:
solve problem
}
But in the example above, remember that the code could be rewritten as:
void function1(void)
{
for( ... )
if (problem)
{
solve problem
return;
}
}
5.5 Break and Continue
5.5.1 Break statement
Break statement is usually used to terminate a case in the switch statement. Break
statement in loops to instantly terminates the loop and program control goes to the
next statement after the loop.
If break statement is used in nested loops (i.e., loop within another loop), the break
statement will end the execution of the inner loop and program control goes back to
outer loop.
Syntax :
break;
Page14
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
5.5.2 Continue statement
In C programming language the continue statement works slightly similar to the break
statement. The continue restarts the loop with the next value of item. All the line code
below continue statement is skips.
Syntax :
continue;
In the for loop, continue statement skips the test condition and increment value of the
variable to execute again and in the while and do...while loops, continue skips all the
statements and program control goes to at the end of loop for tests condition.
6. Functions
6.1 Function Basics
6.1.1 Building Blocks of Programs
Functions like main, printf and scanf. We have already come through. All C programs
made up of one or more functions. There must be one and only one main function. All
functions are at the same level - there is no nesting.
6.1.2 Return Value
Including main, all functions can return a value. Void Return type is specified if
function is returning no value (int, float etc.), pointers structures, unions, or will not
return anything (void) but they cannot return an array or a function.
Page15
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
6.1.3 Function Parameters
Any function (as well as main) can receive some values called parameters. While
calling a function we must pass values of parameters.
Format of Function:
< return_type> < function_name>(parameters...)
{
}
Only values of the parameters to the function at the time of calling it. If in definition
of function contains void as parameter then function will not accept any parameter.
Calling the expressions specified as arguments in a function call and variables listed as
parameters in the function definition is very usual. For example, in the following call
of function, the expressions x and y*2 are the arguments passed to the function. The
values of x and y will be copied into the parameters p and q. The variables given in the
function definition are called as formal argument and the expression given in the
function call are called as the actual argument.
cal_area(a, b*2);
6.2 Definition and Declaration
A function definition contains function name, parameters, its code and return type and
a function declaration contains only name and return type.
User can define a function only once but it can be declared several times.
Declaration of function syntax:
< return_type> < function_name>(arguments... );
/* Declaration of area() */
int area(int x, int y);
int main()
{
int x=10, y=25; printf(''%dn'',area(x,y)));
return 0;
}
Page16
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
Definition of function syntax:
< return_type> < function_name>(arguments)
{
Body of function;
}
/* Definition of area() */
int area(int x, int y)
{
int z;
z = x*y;
retrun z; }
6.3 Standard Header Files
Standard header files contains Prototypes of the library functions. For example, math.h
contains prototypes for mathematical operations.
Some standard header files are:
1. stdio.h, printf, scanf, putchat and etc.
2. conio.h has the function getch and clrscr
3. stdlib.h utility functions; number conversions, memory
4. float.h system limits for floating point types
5. math.h mathematical functions
6. string.h string functions
7. assert.h assertions
8. ctype.h character class tests
9. time.h date and time functions
10. limits.h system limits for integral types
11. setjmp.h non-local jumps
12. signal.h signals and error handling
13. stdarg.h variable length parameter lists
Use the #include (preprocessor directive) and give angle brackets around the name of
the file to include these standard header files in your program.
Page17
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
7. Scope, Blocks & Variables
7.1 Blocks and Scope
C is a block structured language. Blocks are enclosed by { and }. Blocks can be
defined wherever a C statement could be used. No semi-colon is required after the
closing brace of a block.
Variable Scope
Refers to where variables are declared.
Global variable - are declared outside any functions, usually at top of program. They
can be used by later blocks of code:
int g;
int main(void)
{
g = 0;
}
Local variables - are declared inside a function or blocks are local variables. The
scope of local variables will be within the function only. These variables are declared
within the function and can’t be accessed outside the function.
void main()
{
int g;
g=2;
printf(''g= %d'',&g);
}
7.2 Variable Storage Classes
auto
The default class. Automatic variables are local to their block. Their storage space is
reclaimed on the exit from the block.
register
If possible, the variable will be stored in a processor register. May give faster access to
the variable. If register storage is not possible, then the variable will be of automatic
class. Use of the register class is not recommended, as the compiler should be abe to
make better judgment about which variables to hold in registers, in fact injudicious use
of register values may slow down the program.
Page18
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
static
On exit from block, static variables are not reclaimed. They keep their value. On re-
entry to the block the variable will have its old value.
extern
Allows access to external variables. An external variable is either a global variable or
a variable defined in another source file. External variables are defined outside of any
function.(Note: Variables passed to a function and modified by way of a pointer are
not external variables)
static external
External variables can be accessed by any function in any source file program. Static
external variables can only be accessed variable declaration.
7.3 Definition & Declaration
Definition is the place where variable is created (allocated storage).
Declaration is a place where nature (type) of variable is stated, but no storage is
allocated.
Initialization means assigning a value to the variable.
Variables can be declared many times, but defined only once. Memory space is not
allocated for a variable while declaration. It happens only on variable definition.
Variable declaration syntax:
data_type variable_name;
example;
int a, b, c;
char flag;
Variable initialization syntax:
data_type variable_name = value;
Page19
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
example;
int a = 50;
char flag = 't';
7.4 Initialization of Variables
Initialization means assigning a value to the variable.
If variables are not explicitly initialized, then external and static variables are
initialized to zero; pointers (see ch 8) are initialized to NULL ; auto and register
variables have undefined values.
int x = 1;
char quote = ''';
long day = 60 * 24;
int len = strlen(s);
External and static initialization done once only. Auto and register initialization done
each time block is entered. External and static variables cannot be initialized with a
value that is not known until run-time; the initializer must be a constant expression.
8. Arrays, Pointer and String
8.1 Arrays
Array is a collection of similar data type items. Arrays are used to store group of data
of same data type. Arrays can of any data type. Arrays must have constant size.
Continuous memory locations are used to store array. Array index always starts with
0.
Example for Arrays:
int a[5]; // integer array
char a[5]; // character(string) array
Types of Arrays:
1. One Dimensional Array
2. Two Dimensional Array
3. Multi-Dimensional Array
Page20
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
8.1.1 One Dimensional Array
Array declaration
int age [5];
Array initialization
int age[5]={0, 1, 2, 3, 4, 5};
Accessing array
age[0]; /*0_is_accessed*/
age[1]; /*1_is_accessed*/
age[2]; /*2_is_accessed*/
8.1.2 Two Dimensional Array
Two dimensional arrays is combination of rows and columns.
Array declaration
int arr[2][2];
Array initialization
int arr[2][2] = {{1,2}, {3,4}};
Accessing array
arr [0][0] = 1;
arr [0][1] = 2;
arr [1][0] = 3;
arr [1][1] = 4;
8.1.3 Multi-Dimensional Array
C programming language allows programmer to create arrays of arrays known as
multi-dimensional arrays.
For example:
float a[2][4][3];
Page21
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
8.1.4 Passing Array To Function
In C we can pass entire Arrays to functions as an argument.
For example.
#include <stdio.h>
void display(int a)
{
int i;
for(i=0;i < 4;i++){
printf("%d",a[i]);
}
}
int main(){
int c[]={1,2,3,4};
display(c);
//Passing array to display.
return 0;
}
***See programs section of this book for example of —Pointer
8.2 Pointer
Pointer is a variable that stores the address of another variable. They can make some
things much easier; help improve your program's efficiency, and even allow you to
handle unlimited amounts of data.
C Pointer is used to allocate memory dynamically i.e at run time. The variable might
be any of the data type such as int, float, char, double, short etc.
Syntax : Pointers require a bit of new syntax because when you have a pointer, you
need the ability to both request the memory location it stores and the value stored at
that memory location.
data_type *ptr_name;
Example:
int *a; char *a;
Where, * is used to denote that ''a'' is pointer variable and not a normal variable.
Page22
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
Key points to remember about pointers in C:
1. Normal variable stores the value whereas pointer variable stores the address of
the variable.
2. The content of the C pointer always be a whole number i.e address.
3. Always C pointer is initialized to null, i.e. int *p = null.
4. The value of null pointer is 0.
5. & symbol is used to get the address of the variable.
6. * symbol is used to get the value of the variable that the pointer is pointing to.
7. If pointer is assigned to NULL, it means it is pointing to nothing.
8. Two pointers can be subtracted to know how many elements are available
between these two pointers.
9. But, Pointer addition, multiplication, division are not allowed.
10. The size of any pointer is 2 byte (for 16 bit compiler).
Example program for pointer in C:
#include
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you
do not have exact address to be assigned. This is done at the time of variable
declaration. A pointer that assigned NULL is called a null pointer.
Example:
int * ptr = NULL
The value of ptr is 0
Page23
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
Pointer Arithmetic
As you understood pointer is an address which is numeric value; therefore, you can
perform arithmetic operations on a pointer just as you can a numeric value. There are
four arithmetic operators that can be used on pointers: ++, --, +, and -.
Example:
ptr++;
ptr--;
ptr+21;
ptr-10;
If a char pointer pointing to address 100 is incremented (ptr++) then it will point to
memory address 101.
Pointers vs Arrays
Pointers and arrays are strongly related. In fact, pointers and arrays are
interchangeable in many cases. For example, a pointer that points to the beginning of
an array can access that array by using either pointer arithmetic or array-style
indexing.
int main ()
{
int var[3] = {1, 2, 3};
int *ptr;
printf("%d n",*ptr);
ptr++;
printf("%d n",*ptr);
return 0;
}
this code will return :
1
2
Page24
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
Pointer to Pointer
A pointer to a pointer is a form of multiple indirections or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer to a
pointer, the first pointer contains the address of the second pointer, which points to the
location that contains the actual value.
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var :%d n", var);
printf("Value available at *ptr :%d n",*ptr);
printf("Value available at **pptr :%dn",**pptr);
return 0;
}
this code will return
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
8.3 String
A string is simply an array of characters which is terminated by null characters which
shows the end of the string. Strings are always enclosed by double quotes. Whereas,
characters enclosed by single quotes in C. This declaration and initialization create a
string with the word ―AKKI‖. To hold the 0 (null character) at the end of the array,
the size of array is one more than number of characters in the word "AKKI".
char my_name[5] = {'A', 'K', 'K', 'I','0'};
we can also write the above statement as follows:
char my_name[] = "AKKI";
Page25
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
C String functions:
To use string functions programmer must import String.h header file. String.h header
supports all the string functions in C language.
All the string functions are given below.
1. strcat ( ) Concatenates str2 at the end of str1.
2. strncat ( ) appends a portion of string to another.
3. strcpy ( ) Copies str2 into str1.
4. strncpy ( ) copies given number of characters of one string to another.
5 strlen ( ) gives the length of str1.
6. strcmp ( ) Returns 0 if str1 is same as str2. Returns
7. strcmpi ( ) Same as strcmp() function. But, this function negotiates case. ―A‖ and
―a‖ are treated as same.
8. strchr ( ) Returns pointer to first occurrence of char in str1.
9. strrchr ( ) last occurrence of given character in string is found.
10. strstr ( ) Returns pointer to first occurrence of str2 in stri1.
11. strrstr ( ) Returns pointer to last occurrence of str2 in str1.
12. strdup ( ) duplicates the string
13. strlwr ( ) converts string to lowercase
14. strupr ( ) converts string to uppercase
15. strrev ( ) reverses the given string
16. strset ( ) sets all character in a string to given character
17. strnset ( ) It sets the portion of characters in a string to a given character.
18. strtok ( ) tokenizing given string using delimiter
See Programs section of this book for example of this functions.
9. Structure & Union
9.1 Structure
In Array we can store data of one type only, but structure is a variable that gives
facility of storing data of different data type in one variable.
Structures are variables that have several parts; each part of the object can have
different types. Each part of the structure is called a member of the structure.
# Declaration
Consider basic data of student :
roll_no, class, name, age, address.
Page26
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
A structure data type called student can hold all this information:
struct student {
int roll_no
char class
char name[25];
int age;
char address[50];
};
before the final semicolon, At the end of the structure's definition, we can specify one
or more structure variables.
There is also another way of declaring variables given below,
struct student s1;
# Initialization
Structure members can be initialized at declaration. This is same as the initialization of
arrays; the values are listed inside braces. The structure declaration is preceded by the
keyword static.
static struct student akki ={1234,''comp'',''akki'',20,''mumbai”};
# Accessing structure data
To access a given member the dot notation is use. The ―dot‖ is called the member
access operator.
struct student s1;
s1.name = ''Akki'';
s1.roll_no = 1234
# scope
A structure type declaration can be local or global, depending upon where the
declaration is made.
Page27
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
9.2 Union
C Union is also like structure, i.e. collection of different data types which are grouped
together. Each element in a union is called member.
Union and structure both are same, except allocating memory of their members.
Structure allocates storage space for each member separately. Whereas, union
allocates one common storage for all its members.
Syntax
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example
union student
{
int id;
char name[10];
char address[50];
};
Initializing and Declaring union variable
union student data;
union student data = {001,''AKKI'', ''mumbai''};
Accessing union members
data.id
data.name
data.address
Page28
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
10 Files
10.1 File Operations and Functions
10.1.1 File Pointers
It is not enough to just display the data on the screen. We need to save it because
memory is volatile and its contents would be lost once program terminated, so if we
need some data again there are two ways one is retype via keyboard to assign it to
particular variable, and other is regenerate it via programmatically both options are
tedious. At such time it becomes necessary to store the data in a manner that can be
later retrieved and displayed either in part or in whole. This medium is usually a ''file''
on the disk.
Introduction to file
Until now we have been using the functions such as scanf, printf, getch, putch and etc.
to read and write data on the variable and arrays for storing data inside the programs.
But this approach poses the following programs.
1. The data is lost when program terminated or variable goes out of scope.
2. Difficulty to use large volume of data.
We can overcome these problems by storing data data on secondary devices such as
Hard Disk. The data is stored on the devices using the concept of ―file”.
A file is collection of related records, a record is composed of several fields and field
is a group of character.
The most straightforward use of files is via a file pointer.
FILE *fp;
fp is a pointer to a file.
The type FILE, is not a basic type, instead it is defined in the header file stdio.h, this
file must be included in your program.
Page29
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
10.1.2 File Operations
1. Create a new file.
2. Open an existing file
3. Read from file
4. Write to a file
5. Moving a specific location in a file (Seeking)
6. Closing File
10.1.3 Opening a File
fp = fopen(filename, mode);
The filename and mode are both strings.
Here modes can be
"r" read
"w" write, overwrite file if it exists
"a" write, but append instead of overwrite
"r+" read & write, do not destroy file if it exists
"w+" read & write, but overwrite file if it exists
"a+" read & write, but append instead of overwrite
"b" may be appended to any of the above to force text mode.
Example
FILE *fp;
fp=fopen(''input.txt'',''r''); //Opens inputs.txt file in read mode
fclose(fp); //close file
Sequential file access is performed with the following library functions.
1. fopen() - Create a new file
2. fclose() - Close file
3. getc() - Read character from file
4. putc() - Write character to a file
5. getw() - Read Integer from file
6. putw() - Write Integer to a file
7. fprintf() - Write set of data values
8. fscanf() - Read set of data
Page30
L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO
11. Preprocessor Directives
11.1 C Preprocessor Directives
Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with
―#‖ symbol. Below is the list of preprocessor directives that C language offers.
1 Macro
syntax:
#define
This macro defines constant value and can be any of the basic data types.
2 Header file inclusion
syntax:
#include <file_name>
The source code of the file ''file_name'' is included in the main program at the
specified place.
3 Conditional compilations
syntax:
#ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in source program before compilation with
respect to the condition.
4 Other directives
syntax:
#undef, #pragma
#undef is used to un-define a defined macro variable.
#Pragma is used to call a function before and after main function in a C Program.
- END -

More Related Content

What's hot (20)

Fortran 95
Fortran 95Fortran 95
Fortran 95
 
Assignment4
Assignment4Assignment4
Assignment4
 
Fortran introduction
Fortran introductionFortran introduction
Fortran introduction
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONS
 
Handout#10
Handout#10Handout#10
Handout#10
 
Handout#01
Handout#01Handout#01
Handout#01
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Intr fortran90
Intr fortran90Intr fortran90
Intr fortran90
 
Embedded c
Embedded cEmbedded c
Embedded c
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
 
Assignment1
Assignment1Assignment1
Assignment1
 
Handout#06
Handout#06Handout#06
Handout#06
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
Assignment11
Assignment11Assignment11
Assignment11
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
Managing I/O operations In C- Language
Managing I/O operations In C- LanguageManaging I/O operations In C- Language
Managing I/O operations In C- Language
 

Similar to Introduction to C Language - Version 1.0 by Mark John Lado

C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
 
Complete c programming presentation
Complete c programming presentationComplete c programming presentation
Complete c programming presentationnadim akber
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
 
Microcontroller lec 3
Microcontroller  lec 3Microcontroller  lec 3
Microcontroller lec 3Ibrahim Reda
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topicsveningstonk
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
C programming course material
C programming course materialC programming course material
C programming course materialRanjitha Murthy
 

Similar to Introduction to C Language - Version 1.0 by Mark John Lado (20)

C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
Complete c programming presentation
Complete c programming presentationComplete c programming presentation
Complete c programming presentation
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
C structure
C structureC structure
C structure
 
Microcontroller lec 3
Microcontroller  lec 3Microcontroller  lec 3
Microcontroller lec 3
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C Language Presentation.pptx
C Language Presentation.pptxC Language Presentation.pptx
C Language Presentation.pptx
 
C++ Constructs.pptx
C++ Constructs.pptxC++ Constructs.pptx
C++ Constructs.pptx
 
Learn C
Learn CLearn C
Learn C
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Programming in c by pkv
Programming in c by pkvProgramming in c by pkv
Programming in c by pkv
 
C programming course material
C programming course materialC programming course material
C programming course material
 
Cpp
CppCpp
Cpp
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 

More from Mark John Lado, MIT

Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...
Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...
Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...Mark John Lado, MIT
 
Optimizing Embedded System Device Communication with Network Topology Design
Optimizing Embedded System Device Communication with Network Topology DesignOptimizing Embedded System Device Communication with Network Topology Design
Optimizing Embedded System Device Communication with Network Topology DesignMark John Lado, MIT
 
Embedded Systems IO Peripherals Wireless Communication.pdf
Embedded Systems IO Peripherals Wireless Communication.pdfEmbedded Systems IO Peripherals Wireless Communication.pdf
Embedded Systems IO Peripherals Wireless Communication.pdfMark John Lado, MIT
 
Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...
Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...
Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...Mark John Lado, MIT
 
ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...
ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...
ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...Mark John Lado, MIT
 
4 Module - Operating Systems Configuration and Use by Mark John Lado
4 Module - Operating Systems Configuration and Use by Mark John Lado4 Module - Operating Systems Configuration and Use by Mark John Lado
4 Module - Operating Systems Configuration and Use by Mark John LadoMark John Lado, MIT
 
3 Module - Operating Systems Configuration and Use by Mark John Lado
3 Module - Operating Systems Configuration and Use by Mark John Lado3 Module - Operating Systems Configuration and Use by Mark John Lado
3 Module - Operating Systems Configuration and Use by Mark John LadoMark John Lado, MIT
 
1 Module - Operating Systems Configuration and Use by Mark John Lado
1 Module - Operating Systems Configuration and Use by Mark John Lado1 Module - Operating Systems Configuration and Use by Mark John Lado
1 Module - Operating Systems Configuration and Use by Mark John LadoMark John Lado, MIT
 
2 Module - Operating Systems Configuration and Use by Mark John Lado
2 Module - Operating Systems Configuration and Use by Mark John Lado2 Module - Operating Systems Configuration and Use by Mark John Lado
2 Module - Operating Systems Configuration and Use by Mark John LadoMark John Lado, MIT
 
PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...Mark John Lado, MIT
 
PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...Mark John Lado, MIT
 
PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...Mark John Lado, MIT
 
Dart Programming Language by Mark John Lado
Dart Programming Language by Mark John LadoDart Programming Language by Mark John Lado
Dart Programming Language by Mark John LadoMark John Lado, MIT
 
Computer hacking and security - Social Responsibility of IT Professional by M...
Computer hacking and security - Social Responsibility of IT Professional by M...Computer hacking and security - Social Responsibility of IT Professional by M...
Computer hacking and security - Social Responsibility of IT Professional by M...Mark John Lado, MIT
 
A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...
A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...
A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...Mark John Lado, MIT
 
IT Security and Management - Semi Finals by Mark John Lado
IT Security and Management - Semi Finals by Mark John LadoIT Security and Management - Semi Finals by Mark John Lado
IT Security and Management - Semi Finals by Mark John LadoMark John Lado, MIT
 
IT Security and Management - Security Policies
IT Security and Management - Security PoliciesIT Security and Management - Security Policies
IT Security and Management - Security PoliciesMark John Lado, MIT
 
Systems Administration - MARK JOHN LADO
Systems Administration - MARK JOHN LADOSystems Administration - MARK JOHN LADO
Systems Administration - MARK JOHN LADOMark John Lado, MIT
 
IT Security and Management - Prelim Lessons by Mark John Lado
IT Security and Management - Prelim Lessons by Mark John LadoIT Security and Management - Prelim Lessons by Mark John Lado
IT Security and Management - Prelim Lessons by Mark John LadoMark John Lado, MIT
 

More from Mark John Lado, MIT (20)

Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...
Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...
Exploring Parts of Speech, Creating Strong Objectives, and Choosing the Right...
 
Optimizing Embedded System Device Communication with Network Topology Design
Optimizing Embedded System Device Communication with Network Topology DesignOptimizing Embedded System Device Communication with Network Topology Design
Optimizing Embedded System Device Communication with Network Topology Design
 
Embedded Systems IO Peripherals Wireless Communication.pdf
Embedded Systems IO Peripherals Wireless Communication.pdfEmbedded Systems IO Peripherals Wireless Communication.pdf
Embedded Systems IO Peripherals Wireless Communication.pdf
 
Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...
Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...
Implementing the 6S Lean Methodology for Streamlined Computer System Maintena...
 
ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...
ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...
ISO IEC 25010 2011 Systems and Software Quality Requirements and Evaluation S...
 
4 Module - Operating Systems Configuration and Use by Mark John Lado
4 Module - Operating Systems Configuration and Use by Mark John Lado4 Module - Operating Systems Configuration and Use by Mark John Lado
4 Module - Operating Systems Configuration and Use by Mark John Lado
 
3 Module - Operating Systems Configuration and Use by Mark John Lado
3 Module - Operating Systems Configuration and Use by Mark John Lado3 Module - Operating Systems Configuration and Use by Mark John Lado
3 Module - Operating Systems Configuration and Use by Mark John Lado
 
1 Module - Operating Systems Configuration and Use by Mark John Lado
1 Module - Operating Systems Configuration and Use by Mark John Lado1 Module - Operating Systems Configuration and Use by Mark John Lado
1 Module - Operating Systems Configuration and Use by Mark John Lado
 
2 Module - Operating Systems Configuration and Use by Mark John Lado
2 Module - Operating Systems Configuration and Use by Mark John Lado2 Module - Operating Systems Configuration and Use by Mark John Lado
2 Module - Operating Systems Configuration and Use by Mark John Lado
 
PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 1 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
 
PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 2 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
 
PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
PART 3 CT-318-Microprocessor-Systems Lesson 3 - LED Display by Mark John Lado...
 
Dart Programming Language by Mark John Lado
Dart Programming Language by Mark John LadoDart Programming Language by Mark John Lado
Dart Programming Language by Mark John Lado
 
What is CRUD in TPS?
What is CRUD in TPS?What is CRUD in TPS?
What is CRUD in TPS?
 
Computer hacking and security - Social Responsibility of IT Professional by M...
Computer hacking and security - Social Responsibility of IT Professional by M...Computer hacking and security - Social Responsibility of IT Professional by M...
Computer hacking and security - Social Responsibility of IT Professional by M...
 
A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...
A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...
A WIRELESS DIGITAL PUBLIC ADDRESS WITH VOICE ALARM AND TEXT-TO-SPEECH FEATURE...
 
IT Security and Management - Semi Finals by Mark John Lado
IT Security and Management - Semi Finals by Mark John LadoIT Security and Management - Semi Finals by Mark John Lado
IT Security and Management - Semi Finals by Mark John Lado
 
IT Security and Management - Security Policies
IT Security and Management - Security PoliciesIT Security and Management - Security Policies
IT Security and Management - Security Policies
 
Systems Administration - MARK JOHN LADO
Systems Administration - MARK JOHN LADOSystems Administration - MARK JOHN LADO
Systems Administration - MARK JOHN LADO
 
IT Security and Management - Prelim Lessons by Mark John Lado
IT Security and Management - Prelim Lessons by Mark John LadoIT Security and Management - Prelim Lessons by Mark John Lado
IT Security and Management - Prelim Lessons by Mark John Lado
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Introduction to C Language - Version 1.0 by Mark John Lado

  • 1. Learn Programming with C Language Compiled and Modified by: Mark John Perez - Lado Information System Enthusiast Gathering Data Designing Testing
  • 2. Page2 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 1. Introduction to C Language 1.1 Introduction The C programming language is a general-purpose, high – level language (generally denoted as structured language). C programming language was at first developed by Dennis M. Ritchie at At&T Bell Labs. C is one of the most commonly used programming languages. It is simple and efficient therefore it becomes best among all. It is used in all extents of application, mainly in the software development. Many software's & applications as well as the compilers for the other programming languages are written in C also Operating Systems like Unix, DOS and windows are written in C. C has many powers, it is simple, stretchy and portable, and it can control system hardware easily. It is also one of the few languages to have an international standard, ANSI C. 1.2 Advantages of C 1. Fast, Powerful & efficient 2. Easy to learn. 3. It is portable 4. ''Mid-level'' Language 5. Widely accepted language 6. Supports modular programming style 7. Useful for all applications 8. C is the native language of UNIX 9. Easy to connect with system devices/assembly 2. An Example of C program 2.1 Structure of program /* This program prints Hello World on screen */ #include <stdio.h> #include <conio.h> void main() { clrscr(); printf(''Hello Worldn''); getch(); }
  • 3. Page3 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 1 . /* This program ... */ The symbols/* and*/ used for comment. This Comments to provide useful information about program to humans who use it. 2. #include<stdio.h> Is the header file for standard input and output. This is useful for getting the input from the user(Keyboard) and output result text to the monitor(Screen) 3. #include <conio.h> has the function getch(), clrscr() and etc. 4. void main() Is a main function in C language. Void means nothing return any value, this function is used to execute the program. Without main() the program can compile but cannot run. 5. clrscr(); This function is used to clear the output screen. 6. { } Braces surround the body of the function, which may have one or more instructions/statements 7. printf() It is a library function that is used to print data on the user screen. 8. ''Hello Worldn'' Is a string that will be displayed on user screen. n is the newline character. ; a semicolon ends a statement. 9. getch(); It reads character from keyboard. C is case sensitive language, so the names of the functions must be typed in lower case as above. We can use white spaces, tabs & new line characters to make our code easy to read.
  • 4. Page4 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 3. Variables and Operators 3.1 Variables 3.1.1 Variable Declaration Usually Variables are declared before use either at the first of the block of code after the opening { and before any other statements or outside a function. -------------------------- int a,b; /* global variables */ main() { float a; /* local variables */ } -------------------------- Local variables can only be accessed within that function only whereas Global variables can access in whole program. 3.1.2 Variable Types There are many 'built-in' data types in C. 1. short int -128 to 127 (1 byte) 2. unsigned short int 0 to 255 (1 byte) 3. char 0 to 255 or -128 to +127 (1 byte) 4. unsigned char 0 to 255 (1 byte) 5. signed char -128 to 127 (1 byte) 6. int -32,768 to +32,767 (2 bytes) 7. unsigned int 0 to +65,535 (2 bytes) 8. long int -2,147,483,648 to +2,147,483,647 (4 bytes) 9. unsigned long int 0 to 4,294,967,295 (4 bytes) 10. float single precision floating point (4 bytes) 11. double double precision floating point (8 bytes) 12. long double extended precision floating point (10 bytes)
  • 5. Page5 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 3.1.3 Variable Names We can use any combination of letters and numbers for Variable and function names but it must start with a letter. We can use Underscore (_) as a letter in variable name and can begin with an underscore. But identifiers beginning with an underscore are reserved, and identifiers beginning with an underscore followed by a lower case letter are reserved for file scope identifiers. Therefore using underscore as starting letter is not desirable. Akki and akki are different identifiers because upper and lower case letters are treated as different identifiers. 3.2 Operators An operator is a symbol. Compiler identifies Operator and performs specific mathematical or logical operation. C provides following operators: 1. Arithmetic Operators 2. Increment and Decrement Operators 3. Relational Operators 4. Logical Operators 5. Cast Operators 6. Bitwise Operators 7. Assignment Operators 3.2.1 Arithmetic Operators * - multiplication / - division % - remainder after division (modulo arithmetic) + - addition - - subtraction and unary minus 3.2.2 Increment and Decrement Operators Increment and decrement operators are used to add or subtract 1 from the current value of oprand. ++ - increment -- - decrement
  • 6. Page6 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO Increment and Decrement operators can be prefix of postfix. In the prefix style the value of oprand is changed before the result of expression and in the postfix style the variable is modified after result. For example. a = 9; b = a++ + 5; /* a=10 b=14 */ a = 3; b = ++a + 6; /* a=10 b=15 */ 3.2.3 Relational Operators == - equal. != - Not equal. > < - Greater than/less than >= - greater than or equal to <= - less than or equal to 3.2.4 Logical Operators && Called Logical AND operator. If both the operands are non-zero, then condition becomes true. || Called Logical OR Operator. If any of the two operands are non-zero, then condition becomes true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. 3.2.5 Cast Operators Cast operators are used to convert a value from one to another type. (float) sum; converts type to float (int) fred; converts type to int
  • 7. Page7 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 3.2.6 Bitwise Operators Bitwise operators performs operation on actual bits present in each byte of a variable. Each byte contain 8 bits, each bit can store the value 0 or 1. ~ - one's complement & - bitwise AND ^ - bitwise XOR | - bitwise OR << - left shift (binary multiply by 2) >> - right shift (binary divide by 2) 3.2.7 Assignment Operators = - assign += - assign with add -= - assign with subtract *= - assign with multiply /= - assign with divide %= - assign with remainder >>= - assign with right shift <<= - assign with left shift &= - assign with bitwise AND ^= - assign with bitwise XOR |= - assign with bitwise OR For example, a = a + 64; is same as a += 64;
  • 8. Page8 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 4. Input & Output 4.1 Formatted IO – printf and scanf 4.1.1 Formatted Output - printf It takes text and values from within the program and sends it out onto the screen. printf(''%f is your weightn'', w); In the above program statement: ''%f is your weightn'' - is the control string w - is the variable to be printed %f - meaning that a floating point value is to be printed. The number of conversion specifications and the number of variables following the control string must be same, and that the conversion character is correct for the type of parameter. 4.1.2 Formatted Input – scanf scanf is used to get input from user and to store it in the specific variable(s). scanf(''%d'', &x); read a decimal integer from the keyboard and store the value in the memory address of the variable x. 4.1.3 Character Escape Sequences There are several character escape sequences which can be used in place of a character constant or within a string. a - alert (bell) b - backspace f - formfeed n - newline r - carriage return t - tab v - vertical tab - backslash ? - question mark ' - quote '' - double quote ooo - character specified as an octal number xhh - character specified in hexadecimal
  • 9. Page9 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 4.2 Character IO – getchar & putchar getchar and putchar are used for the input or output only one character. getchar() - It returns an int which is either EOF (indicating end-of-file) or the next character in the standard input stream. putchar(c) - Puts the character on the output stream. int main() { int a; a = getchar(); /* read and assign character to c */ putchar(a); /* print c on the screen */ return 0; } 5. Flow of control 5.1 Conditional branching – if 5.1.1 if statement An if statement contains a Boolean expression and block of statements enclosed within braces. Structure of if statement: if (boolean expression ) /* if expression is true */ statements... ; /* Execute statements */ If the Boolean expression is true then statement block is executed otherwise (if false) program directly goes to next statement without executing statement block. 5.1.2 if...else statement
  • 10. Page10 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO If statement block with else statement is known as as if…else statement. Else portion is non-compulsory. Structure of if...else: if(condition) { statements... } else { statements... } If the condition is true, then compiler will execute the if block of statements, if false then else block of statements will be executed. We can use multiple if-else for one inside other this is called as Nested if-else. 5.2 Conditional Selection – switch switch() A switch statement is used instead of nested if...else statements. It is multiple branch decision of statement of C. A switch statement tests a variable with list of values for equivalence. Each value is called a case. The case value must be a constant integer. Structure of switch() statement : switch (expression) { case value: statements... case value: statements... default : statements... } Individual case keyword and a semi-colon (:) is used for each constant. Switch tool is used for skipping to particular case, after jumping to that case it will execute all statements from cases beneath that case this is called as ''Fall Through''. In the example below, for example, if the value 2 is entered, then the program will print two one something else!
  • 11. Page11 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO int main() { int i; printf(''Enter an integer: ''); scanf(''%d'',&i); switch(i) { case 4: printf(''four ''); break; case 3: printf(''three ''); break; case 2: printf(''two ''); case 1: printf(''one ''); default: printf(''something else!''); } return 0; } To avoid fall through, the break statements are necessary to exit the switch. If value 4 is entered, then in case 4 it will just print four and ends the switch. The default label is non-compulsory; it is used for cases that are not present. 5.3 Loops – while & for while loop The while loop calculates the expression before every loop. If the expression is true then block of statements is executed, so it will not execute if the condition is initially false. It needs the parenthesis like the if statement. while ( expression ) /* while expression is true do following*/ statements... ; Do While loop This is equivalent to a while loop, but it have test condition at the end of the loop. The Do while loop will always execute at least once. do statements ; while ( expression ); /* while expression is true do...*/
  • 12. Page12 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO For loop This is very widely held loop. For loops work like the corresponding while loop shown in the above example. The first expression is treated as a statement and executed, then the second expression is test or condition which is evaluated to see if the body of the loop should be executed. The third expression is increment or decrement which is performed at the end of every iteration/repetition of the loop. for (expr1; expr2; expr3) statements...; In while loop it can happen that the statement will never execute. But in the do-while loop, test condition is based at the end of loop therefore the block of statement will always execute at least once. This is the main difference between the while and the do- while loop. For example, to execute a statement 5 times: for (i = 0; i < 5; i++) printf(''%dn'',i); Another way of doing this is: i = 5; while (i--) statements; While using this method, make sure that value of i is greater than zero, or make the test i -->0.
  • 13. Page13 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 5.4 Local Jumps go to We can jump to any statement inside the same function using goto. To spot the end of point of the jump a label (tag) is used. goto statement is not to ideal to choose in any programming language because it makes difficult to trace the flow of a program, makes the program hard to understand, and to guess the output. void any_function(void) { for( ... ) if (problem) goto error; error: solve problem } But in the example above, remember that the code could be rewritten as: void function1(void) { for( ... ) if (problem) { solve problem return; } } 5.5 Break and Continue 5.5.1 Break statement Break statement is usually used to terminate a case in the switch statement. Break statement in loops to instantly terminates the loop and program control goes to the next statement after the loop. If break statement is used in nested loops (i.e., loop within another loop), the break statement will end the execution of the inner loop and program control goes back to outer loop. Syntax : break;
  • 14. Page14 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 5.5.2 Continue statement In C programming language the continue statement works slightly similar to the break statement. The continue restarts the loop with the next value of item. All the line code below continue statement is skips. Syntax : continue; In the for loop, continue statement skips the test condition and increment value of the variable to execute again and in the while and do...while loops, continue skips all the statements and program control goes to at the end of loop for tests condition. 6. Functions 6.1 Function Basics 6.1.1 Building Blocks of Programs Functions like main, printf and scanf. We have already come through. All C programs made up of one or more functions. There must be one and only one main function. All functions are at the same level - there is no nesting. 6.1.2 Return Value Including main, all functions can return a value. Void Return type is specified if function is returning no value (int, float etc.), pointers structures, unions, or will not return anything (void) but they cannot return an array or a function.
  • 15. Page15 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 6.1.3 Function Parameters Any function (as well as main) can receive some values called parameters. While calling a function we must pass values of parameters. Format of Function: < return_type> < function_name>(parameters...) { } Only values of the parameters to the function at the time of calling it. If in definition of function contains void as parameter then function will not accept any parameter. Calling the expressions specified as arguments in a function call and variables listed as parameters in the function definition is very usual. For example, in the following call of function, the expressions x and y*2 are the arguments passed to the function. The values of x and y will be copied into the parameters p and q. The variables given in the function definition are called as formal argument and the expression given in the function call are called as the actual argument. cal_area(a, b*2); 6.2 Definition and Declaration A function definition contains function name, parameters, its code and return type and a function declaration contains only name and return type. User can define a function only once but it can be declared several times. Declaration of function syntax: < return_type> < function_name>(arguments... ); /* Declaration of area() */ int area(int x, int y); int main() { int x=10, y=25; printf(''%dn'',area(x,y))); return 0; }
  • 16. Page16 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO Definition of function syntax: < return_type> < function_name>(arguments) { Body of function; } /* Definition of area() */ int area(int x, int y) { int z; z = x*y; retrun z; } 6.3 Standard Header Files Standard header files contains Prototypes of the library functions. For example, math.h contains prototypes for mathematical operations. Some standard header files are: 1. stdio.h, printf, scanf, putchat and etc. 2. conio.h has the function getch and clrscr 3. stdlib.h utility functions; number conversions, memory 4. float.h system limits for floating point types 5. math.h mathematical functions 6. string.h string functions 7. assert.h assertions 8. ctype.h character class tests 9. time.h date and time functions 10. limits.h system limits for integral types 11. setjmp.h non-local jumps 12. signal.h signals and error handling 13. stdarg.h variable length parameter lists Use the #include (preprocessor directive) and give angle brackets around the name of the file to include these standard header files in your program.
  • 17. Page17 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 7. Scope, Blocks & Variables 7.1 Blocks and Scope C is a block structured language. Blocks are enclosed by { and }. Blocks can be defined wherever a C statement could be used. No semi-colon is required after the closing brace of a block. Variable Scope Refers to where variables are declared. Global variable - are declared outside any functions, usually at top of program. They can be used by later blocks of code: int g; int main(void) { g = 0; } Local variables - are declared inside a function or blocks are local variables. The scope of local variables will be within the function only. These variables are declared within the function and can’t be accessed outside the function. void main() { int g; g=2; printf(''g= %d'',&g); } 7.2 Variable Storage Classes auto The default class. Automatic variables are local to their block. Their storage space is reclaimed on the exit from the block. register If possible, the variable will be stored in a processor register. May give faster access to the variable. If register storage is not possible, then the variable will be of automatic class. Use of the register class is not recommended, as the compiler should be abe to make better judgment about which variables to hold in registers, in fact injudicious use of register values may slow down the program.
  • 18. Page18 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO static On exit from block, static variables are not reclaimed. They keep their value. On re- entry to the block the variable will have its old value. extern Allows access to external variables. An external variable is either a global variable or a variable defined in another source file. External variables are defined outside of any function.(Note: Variables passed to a function and modified by way of a pointer are not external variables) static external External variables can be accessed by any function in any source file program. Static external variables can only be accessed variable declaration. 7.3 Definition & Declaration Definition is the place where variable is created (allocated storage). Declaration is a place where nature (type) of variable is stated, but no storage is allocated. Initialization means assigning a value to the variable. Variables can be declared many times, but defined only once. Memory space is not allocated for a variable while declaration. It happens only on variable definition. Variable declaration syntax: data_type variable_name; example; int a, b, c; char flag; Variable initialization syntax: data_type variable_name = value;
  • 19. Page19 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO example; int a = 50; char flag = 't'; 7.4 Initialization of Variables Initialization means assigning a value to the variable. If variables are not explicitly initialized, then external and static variables are initialized to zero; pointers (see ch 8) are initialized to NULL ; auto and register variables have undefined values. int x = 1; char quote = '''; long day = 60 * 24; int len = strlen(s); External and static initialization done once only. Auto and register initialization done each time block is entered. External and static variables cannot be initialized with a value that is not known until run-time; the initializer must be a constant expression. 8. Arrays, Pointer and String 8.1 Arrays Array is a collection of similar data type items. Arrays are used to store group of data of same data type. Arrays can of any data type. Arrays must have constant size. Continuous memory locations are used to store array. Array index always starts with 0. Example for Arrays: int a[5]; // integer array char a[5]; // character(string) array Types of Arrays: 1. One Dimensional Array 2. Two Dimensional Array 3. Multi-Dimensional Array
  • 20. Page20 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 8.1.1 One Dimensional Array Array declaration int age [5]; Array initialization int age[5]={0, 1, 2, 3, 4, 5}; Accessing array age[0]; /*0_is_accessed*/ age[1]; /*1_is_accessed*/ age[2]; /*2_is_accessed*/ 8.1.2 Two Dimensional Array Two dimensional arrays is combination of rows and columns. Array declaration int arr[2][2]; Array initialization int arr[2][2] = {{1,2}, {3,4}}; Accessing array arr [0][0] = 1; arr [0][1] = 2; arr [1][0] = 3; arr [1][1] = 4; 8.1.3 Multi-Dimensional Array C programming language allows programmer to create arrays of arrays known as multi-dimensional arrays. For example: float a[2][4][3];
  • 21. Page21 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 8.1.4 Passing Array To Function In C we can pass entire Arrays to functions as an argument. For example. #include <stdio.h> void display(int a) { int i; for(i=0;i < 4;i++){ printf("%d",a[i]); } } int main(){ int c[]={1,2,3,4}; display(c); //Passing array to display. return 0; } ***See programs section of this book for example of —Pointer 8.2 Pointer Pointer is a variable that stores the address of another variable. They can make some things much easier; help improve your program's efficiency, and even allow you to handle unlimited amounts of data. C Pointer is used to allocate memory dynamically i.e at run time. The variable might be any of the data type such as int, float, char, double, short etc. Syntax : Pointers require a bit of new syntax because when you have a pointer, you need the ability to both request the memory location it stores and the value stored at that memory location. data_type *ptr_name; Example: int *a; char *a; Where, * is used to denote that ''a'' is pointer variable and not a normal variable.
  • 22. Page22 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO Key points to remember about pointers in C: 1. Normal variable stores the value whereas pointer variable stores the address of the variable. 2. The content of the C pointer always be a whole number i.e address. 3. Always C pointer is initialized to null, i.e. int *p = null. 4. The value of null pointer is 0. 5. & symbol is used to get the address of the variable. 6. * symbol is used to get the value of the variable that the pointer is pointing to. 7. If pointer is assigned to NULL, it means it is pointing to nothing. 8. Two pointers can be subtracted to know how many elements are available between these two pointers. 9. But, Pointer addition, multiplication, division are not allowed. 10. The size of any pointer is 2 byte (for 16 bit compiler). Example program for pointer in C: #include int main() { int *ptr, q; q = 50; /* address of q is assigned to ptr */ ptr = &q; /* display q's value using ptr variable */ printf("%d", *ptr); return 0; } NULL Pointers It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that assigned NULL is called a null pointer. Example: int * ptr = NULL The value of ptr is 0
  • 23. Page23 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO Pointer Arithmetic As you understood pointer is an address which is numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -. Example: ptr++; ptr--; ptr+21; ptr-10; If a char pointer pointing to address 100 is incremented (ptr++) then it will point to memory address 101. Pointers vs Arrays Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. int main () { int var[3] = {1, 2, 3}; int *ptr; printf("%d n",*ptr); ptr++; printf("%d n",*ptr); return 0; } this code will return : 1 2
  • 24. Page24 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO Pointer to Pointer A pointer to a pointer is a form of multiple indirections or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value. int main () { int var; int *ptr; int **pptr; var = 3000; ptr = &var; pptr = &ptr; printf("Value of var :%d n", var); printf("Value available at *ptr :%d n",*ptr); printf("Value available at **pptr :%dn",**pptr); return 0; } this code will return Value of var :3000 Value available at *ptr :3000 Value available at **pptr :3000 8.3 String A string is simply an array of characters which is terminated by null characters which shows the end of the string. Strings are always enclosed by double quotes. Whereas, characters enclosed by single quotes in C. This declaration and initialization create a string with the word ―AKKI‖. To hold the 0 (null character) at the end of the array, the size of array is one more than number of characters in the word "AKKI". char my_name[5] = {'A', 'K', 'K', 'I','0'}; we can also write the above statement as follows: char my_name[] = "AKKI";
  • 25. Page25 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO C String functions: To use string functions programmer must import String.h header file. String.h header supports all the string functions in C language. All the string functions are given below. 1. strcat ( ) Concatenates str2 at the end of str1. 2. strncat ( ) appends a portion of string to another. 3. strcpy ( ) Copies str2 into str1. 4. strncpy ( ) copies given number of characters of one string to another. 5 strlen ( ) gives the length of str1. 6. strcmp ( ) Returns 0 if str1 is same as str2. Returns 7. strcmpi ( ) Same as strcmp() function. But, this function negotiates case. ―A‖ and ―a‖ are treated as same. 8. strchr ( ) Returns pointer to first occurrence of char in str1. 9. strrchr ( ) last occurrence of given character in string is found. 10. strstr ( ) Returns pointer to first occurrence of str2 in stri1. 11. strrstr ( ) Returns pointer to last occurrence of str2 in str1. 12. strdup ( ) duplicates the string 13. strlwr ( ) converts string to lowercase 14. strupr ( ) converts string to uppercase 15. strrev ( ) reverses the given string 16. strset ( ) sets all character in a string to given character 17. strnset ( ) It sets the portion of characters in a string to a given character. 18. strtok ( ) tokenizing given string using delimiter See Programs section of this book for example of this functions. 9. Structure & Union 9.1 Structure In Array we can store data of one type only, but structure is a variable that gives facility of storing data of different data type in one variable. Structures are variables that have several parts; each part of the object can have different types. Each part of the structure is called a member of the structure. # Declaration Consider basic data of student : roll_no, class, name, age, address.
  • 26. Page26 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO A structure data type called student can hold all this information: struct student { int roll_no char class char name[25]; int age; char address[50]; }; before the final semicolon, At the end of the structure's definition, we can specify one or more structure variables. There is also another way of declaring variables given below, struct student s1; # Initialization Structure members can be initialized at declaration. This is same as the initialization of arrays; the values are listed inside braces. The structure declaration is preceded by the keyword static. static struct student akki ={1234,''comp'',''akki'',20,''mumbai”}; # Accessing structure data To access a given member the dot notation is use. The ―dot‖ is called the member access operator. struct student s1; s1.name = ''Akki''; s1.roll_no = 1234 # scope A structure type declaration can be local or global, depending upon where the declaration is made.
  • 27. Page27 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 9.2 Union C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member. Union and structure both are same, except allocating memory of their members. Structure allocates storage space for each member separately. Whereas, union allocates one common storage for all its members. Syntax union tag_name { data type var_name1; data type var_name2; data type var_name3; }; Example union student { int id; char name[10]; char address[50]; }; Initializing and Declaring union variable union student data; union student data = {001,''AKKI'', ''mumbai''}; Accessing union members data.id data.name data.address
  • 28. Page28 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 10 Files 10.1 File Operations and Functions 10.1.1 File Pointers It is not enough to just display the data on the screen. We need to save it because memory is volatile and its contents would be lost once program terminated, so if we need some data again there are two ways one is retype via keyboard to assign it to particular variable, and other is regenerate it via programmatically both options are tedious. At such time it becomes necessary to store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is usually a ''file'' on the disk. Introduction to file Until now we have been using the functions such as scanf, printf, getch, putch and etc. to read and write data on the variable and arrays for storing data inside the programs. But this approach poses the following programs. 1. The data is lost when program terminated or variable goes out of scope. 2. Difficulty to use large volume of data. We can overcome these problems by storing data data on secondary devices such as Hard Disk. The data is stored on the devices using the concept of ―file”. A file is collection of related records, a record is composed of several fields and field is a group of character. The most straightforward use of files is via a file pointer. FILE *fp; fp is a pointer to a file. The type FILE, is not a basic type, instead it is defined in the header file stdio.h, this file must be included in your program.
  • 29. Page29 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 10.1.2 File Operations 1. Create a new file. 2. Open an existing file 3. Read from file 4. Write to a file 5. Moving a specific location in a file (Seeking) 6. Closing File 10.1.3 Opening a File fp = fopen(filename, mode); The filename and mode are both strings. Here modes can be "r" read "w" write, overwrite file if it exists "a" write, but append instead of overwrite "r+" read & write, do not destroy file if it exists "w+" read & write, but overwrite file if it exists "a+" read & write, but append instead of overwrite "b" may be appended to any of the above to force text mode. Example FILE *fp; fp=fopen(''input.txt'',''r''); //Opens inputs.txt file in read mode fclose(fp); //close file Sequential file access is performed with the following library functions. 1. fopen() - Create a new file 2. fclose() - Close file 3. getc() - Read character from file 4. putc() - Write character to a file 5. getw() - Read Integer from file 6. putw() - Write Integer to a file 7. fprintf() - Write set of data values 8. fscanf() - Read set of data
  • 30. Page30 L e a r n P r o g r a m m i n g w i t h C L a n g u a g e M.J. LADO 11. Preprocessor Directives 11.1 C Preprocessor Directives Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called preprocessing. Commands used in preprocessor are called preprocessor directives and they begin with ―#‖ symbol. Below is the list of preprocessor directives that C language offers. 1 Macro syntax: #define This macro defines constant value and can be any of the basic data types. 2 Header file inclusion syntax: #include <file_name> The source code of the file ''file_name'' is included in the main program at the specified place. 3 Conditional compilations syntax: #ifdef, #endif, #if, #else, #ifndef Set of commands are included or excluded in source program before compilation with respect to the condition. 4 Other directives syntax: #undef, #pragma #undef is used to un-define a defined macro variable. #Pragma is used to call a function before and after main function in a C Program. - END -