C Programming (Brief Notes)
C Programming (Brief Notes)
Computer Programming
Programming
The act of a programmer writing code
or instructions (program) in a
programming language that instructs
a computer or other electronic device
how to operate or function.
Programming
is a term used to describe the process
of a programmer developing a
program.
Computer programming
(often shortened to
programming or coding)
cntd
Programming language
A programming language is a
computer language programmers
use to develop applications, scripts,
or other set of instructions for a
computer to execute.
Program
A program is a set of instructions for
performing a particular task.
Many program files on IBM
compatible computers commonly
end with a file extension of .BAT,
.EXE, .COM, or .PIF. Executing these
files will commonly open the
program.
Program cntd
A software application, or software
program, is the most commonly
found and run files on a computer. An
example of a software application is
Microsoft Word, which is a word
processor allowing users to create
and write documents. Without
programs, a user may have an
operating computer, but would not be
able to do much with it.
Programmer
An individual who enjoys or writes code,
or develops software for a living. Many
programmers who program for a
profession have a college degree in
computer science. While each job differs,
most programmers are responsible for
creating the software program or parts of
a program, debugging problems, and/or
adding onto a program.
Generation languages
The first generation languages, or 1GL
are low-level languages that are
machine language.
The second generation languages, or
2GL are also low-level languages that
generally consist of assembly
languages.
The third generation languages, or 3GL
are high-level languages such as C.
Generation languages
cntd
The fourth generation languages, or 4GL
are languages that consist of statements
similar to statements in a human language.
Fourth generation languages are commonly
used in database programming and scripts.
The fifth generation languages, or 5GL are
programming languages that contain visual
tools to help develop a program. A good
example of a fifth generation language is
Visual Basic.
Low-level language
Programming language that is more
arcane and difficult to understand.
Some good examples of low-level
languages are assembly and
machine languages
High-level language
A type of advanced computer
programming language that isn't
limited by the type of computer or
for one specific job and is more easily
understood. Today, there are dozens
of high-level languages; some
commonly used high-level languages
are BASIC, C, FORTAN and Pascal.
Machine language
Sometimes referred to as machine
code or object code, machine
language is a collection of binary
digits or bits that the computer
reads and interprets. Machine
language is the only language a
computer is capable of
understanding
Assembly language
Sometimes referred to as assembly or
ASL.
An assembly language is the low-level
programming language designed for a
specific processor.
Assembly language uses structured
commands as substitutions for
numbers allowing humans to read the
code more easily than looking at
binary.
ax,4C00h
21h
C
is general purpose programming
language.
C language was developed by
Dennis Ritchie at Bell
Laboratories in 1972.
It is an offspring of the Basic
combined programming
language called B developed in
1960 at Cambridge University.
C cntd
C runs under a number of operating
systems including MS.DOS. C programs are
efficient, fast and highly portable i.e C
programs written on one computer can be
run on another with little or no modification.
C language is a middle level computer
language.
C is not troublesome like assembly level
language. It combines the features of both
high level language and functionality like
assembly language. It reduces the gap
between high and low level languages.
ANSI C
A standard C version created by ANSI
(American National Standard Institute)
in 1990.
The purpose of this standard is to
enhance the portability and efficient
execution of C language programs on
different computers.
To Date most C compilers have been
designed following ANSI C standard.
Interpreters
An Interpreter reads only one line of
a source program at a time and
converts it into object codes. If an
error occurs, it will instantly be
indicated. The disadvantage of
interpreters is that it consumes
more time for converting a source
program to an object program.
Compilers
A compiler reads the entire program
and converts it to object code. It
provides errors not of one line but of
the entire program. Only error free
programs are executed. It consumes
little time for converting a source
program to object program. Compilers
are preferred when the program
length of an application is large.
Structure of a C Program
Every C program contains a number
of several building blocks known as
functions. Each function performs a
task independently. A function is a
subroutine that may consist of one or
more statements. A C program is
comprised of the following sections:
Global Declaration
This section declares variables that
are used in more than one function.
These variables are known as global
variables. These variables must be
declared outside of all the functions.
Function main()
Every program written in C language
must contain main() function. The empty
parenthesis after main are necessary.
The function main() is the starting point
of every C program. The execution of
the program always begins with the
function main(). Program execution starts
with the opening brace { and ends with
the closing brace }.
Declaration part
The declaration part declares the
entire variables that are used in the
executable part.
The initializations of variables are
also done in this section.
Initialization means providing an
initial value to the variables.
Executable part
This part contains the statements
following the declaration of variables.
This part can contain a set of
statements or a single statement.
These statements are enclosed
between braces.
Comments
Comments are statements that help
programmers understand the flow of
programs. Comments are useful for
documentation. /* comments are
statements placed between
delimiters */
/* the compiler does not execute
comments. */
Introduction To C
Programming language
A Programming language should be able to
support certain kind of data, such as numbers,
characters, strings etc. to get useful output
known as information.
A program is a set of statements for a specific
task, which will be executed in a sequential
form.
These statements or instructions are formed
using certain words and symbols according to
the rules known as syntax rules or grammar
of the language.
Every program must follow accurately the
syntax rules supported by the language.
Letters
Capital A to Z
Small a to z
Digits
All decimal digits 0 to 9
White Spaces
Blank spaces
New line
Special Characters
C/outline)
(See
Delimiters
Are special kind of symbols:
: Colon
Useful for label
; Semi colon
Terminates statements
( ) Parenthesis
used in expressions and
functions
[ ] Square brackets
for array declaration
{}
Curly Brace
Scope of statement
# HashPreprocessor Directive
, Comma Variable separator
The C Keywords
(c/outline)
The C keywords are reserved words
by the compiler.
All C keywords are assigned a fixed
meaning.
The keywords cannot be used as
variable names because they have
fixed jobs.
Identifiers
Are names of variables, functions,
and arrays.
They are user-defined names,
consisting of sequences of letters and
digits, with the letter as the first
character.
Constants: are identifiers whose
value does not change during program
execution.
Variable
Is a data name used for storing a data
value. or
Is defined as a location in the
computer memory which stores a data
type according to the declaration.
Also named an Identifier.
A variable is just a named area of
storage that can hold a single value
(numeric or character).
Variable cntd
A variable is a data object that may
change in value.
A variable can be assigned different values
at different times during the execution of a
program.
It is given a name by means of a definition
and declaration which allocates the
storage space for the data and associates
the storage location with the variable
name.
Data_Type Variable_Name;
int mark1;
float sum, ave;
double answer;
char yr_initial;
State its type and give it a name.
Int = =2 bytes,
float = =4 bytes,
double = =8 bytes,
char = =1
byte.
Constatnts
Constants: are identifiers whose
value does not change during
program execution.
Constatnts cntd
C constants
Numeric Constants
Integer Constants
Real Constants
Character Constants
Integer Constants
These are the sequence of numbers
from 0 to 9 without decimal points or
fractional part or any other symbols.
Requires a min of 2 bytes and a max
of 4 bytes.
Integer Constants can either be
positive or negative.
E.g. 10, 20, +30, -15
Real Constants
Real constants are often known as
floating point constants.
E.g. 2.5, 5.521, 3.14
Real constants can be written in
exponential notation, which contains a
fraction part and an exponential part.
E.g. 2456.123 can be written as
2.4561Xe+3
Single Character
Constants
A character constant is a single
character.
Represented with a single digit or a
single special symbol or white space
enclosed within a pair of single quote
marks.
E.g. a, 7, , $,
String Constants
Are sequences of characters
enclosed within a double quote
marks.
The string may be a combination of
all kinds of symbols.
E.g. Hello, India, 444, a
Declaring Constants
By adding the keyword const before
the declaration. E.g. const int m=10;
The compiler protects the value of
m from modification. The user
cannot assign any value to m.
#define N 10
#define a 15
Where N and a are user-defined
identifiers.
Assignment Statement
Once declared a variable has to be
defined.
An assignment statement stores
values ( of expressions, or other
variables) into variables.
C uses the = assignment
operator for assignment. (storing
values into variables)
Initialising Variables
Providing an initial value into a variable.
Variables declared can be assigned or
initialised using an = assignment
operator.
The declaration and initialisation can
also be done in the same line.
Syntax:
variable_name=constant;
Or data_type Variable_name=constant;
Statements and
Expressions
Having defined variables of different
types as part of your program, one
will need to combine the variables to
make them useful in Expressions.
A simple Statement is an expression
Terminated by a semi-colon (;).
E.g. a=3;
(complete
statement)
Statements and
Expressions cntd
One can assign an expression to a
variable:
E.g.
Sum = a+b;
Arithmetic Expressions
C Operators- Arithmetic
Ther are two types: Binary and Unary
1. Binary Operators
+
a+b addition
- a-b subtraction
* a*b multiplication
/ a/b division
%
a%bmodular remainder division
C Operators- Arithmetic
2.
Unary Operators
Minus
++
increment
-Decrement
&
Address Operator
Size of
Gives the size of a variable
Minus (-): Unary minus is used to indicate
or change the algebraic sign of a value.
Increment and
Decrement Operators
++
- E.g.
Equivalent to:
num = num+1;
num = num-1;
Arithmetic Ordering:
a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
Sizeof()
The sizeof() operator gives the bytes
occupied by a variable. The number
of bytes occupied varies from
variable to variable depending on its
data types.
E.g. int x=2; float y=2;
printf(%d : %d,sizeof(x), sizeof(y));
Ans:
2 : 4
& Address of
The & address of operator prints
address of the variable in the memory.
E.g. int x=2; float y=2;
printf(%d : %d,sizeof(x), sizeof(y));
printf(%u : %u, &x, &y);
Ans:2 : 4
4066
: 25096
Relational Operators
Logical Operators
&&
AND
T AND T = T
T AND F = F
||
OR
NOT
T OR T = T and
T OR F = T,
F OR F = F
Format Specifiers
FS
Type
display
%c
charsingle character
%d
[%i] int signed integer
%e[%E]
float/double exponential
formt
%f float/double
%s
array of characters
sequence
(a string)
flag
flag width.precision
The flag can be any of:
flag
meaning
left justify
+
always display sign
space
display space if there is no sign
0
pad with leading zeros
#
use alternate form of specifier
control codes
Scanf()
scanf(control
string,variable,variable,...)
scanf("%d %d",&i,&j);
In this case the control string specifies
how strings of characters, usually typed
on the keyboard, should be converted
into values and stored in the listed
variables. However there are a number
of important differences as well as
similarities between scanf and printf.
Syntax
When referring to a programming
language or command, syntax is a set of
rules that are associated with the
language or command.
When referring to an error, a syntax error
is an error that is encountered when the
programmer or individual who wrote the
code has not followed the rules of the
language, causing the program to fail.
Execute
A term used to describe the process
of running a computer software
program or command. For example,
each time you open your Internet
browser you're executing the
program
Executable file
An executable file is a file that is used to
perform various functions or operations
on a computer. Unlike a data file, an
executable file cannot generally be read
because it has been compiled. On an IBM
compatible computer, common
executable files are .BAT, .COM, .EXE, and
.BIN. Depending on the operating system
and its setup, there can also be several
other types of executable files
Compile
The process of creating an
executable program from code
written in a compiled programming
language that allows the computer to
run the program without the need of
the programming software used to
create it. es.
Compile
When a program is compiled it is
often compiled for a specific platform
such as an IBM platform, which would
work with any IBM compatible
computers but not other platforms
such as the Apple Macintosh platform.
Below are some examples of
compiled programming language:
C, C++, C#, D, Pascal
Control Loops
Objectives:
Having read this section you should
have an idea about C's:
1.Conditional, or Logical, Expressions
as used
in program control
2.the do while loop
3.the while loop
4.the for loop
Conditions or Logical
Expressions:
The only detail we need to clear up is what
Conditions or Logical
Expressions
The only complication is that the test
for 'something equals something
else' uses the character sequence
== and not =. That's right: a test for
equality uses two equal-signs, as in
a==0, while
an assignment, as in a=0, uses one.
if
The if statement evaluates an
expression. If that expression is true,
then a statement is executed. If an
else clause is given and if the
expression is false, then the else's
statement is executed.
if
Syntax:
if( expression ) statement1;
or
if( expression ) statement1;
else statement2 ;
Examples:
if(loop<3) counter++;
if(x==y) x++;
else y++;
if(z>x) {z=5; x=3; }
else { z=3; x=5; }
switch
A switch statement allows a single
variable to be compared with several
possible constants. If the variable
matches one of the constants, then a
execution jump is made to that point.
A constant can not appear more than
once, and there can only be one
default expression.
Syntax:
switch ( variable )
{
case const:
statements...;
default:
statements...;
}
Examples:
switch(betty)
{
case 1: printf("betty=1\n");
case 2: printf("betty=2\n"); break;
case 3: printf("betty=3\n"); break;
default: printf("Not sure.\n");
}
Examples:
If betty is 1, then two lines are
printed: betty==1 and betty==2. If
betty is 2, then only one line is
printed: betty==2. If betty==3, then
only one line is printed: betty==3. If
betty does not equal 1, 2, or 3, then
"Not sure." is printed.
while
The while statement provides an
iterative loop.
Syntax:
while( expression ) statement...
statement is executed repeatedly as
long as expression is true. The test
on expression takes place before
each execution of statement.
Examples:
while(*pointer!='j') pointer++;
while(counter<5)
{
printf("counter=%i",counter);
counter++;
}
while
Each line of a C program up to the
semicolon is called a statement. The
semicolon is the statement's
terminator. The braces { and }
which have appeared at the beginning
and end of our program unit can also
be used to group together related
declarations and statements into a
compound statement or a block.
while Examples:
#include <stdio.h>
main()
{
while (1 == 1) printf("Hello
World!\n");
}
dowhile
The do...while construct provides an
iterative loop.
Syntax:
do statement... while( expression );
statement is executed repeatedly as
long as expression is true. The test
on expression takes place after each
execution of statement.
dowhile
In the case of the do while loop it will
always execute the code within the
loop at least once, since the condition
controlling the loop is tested at the
bottom of the loop.
The do while loop repeats the instruction
while the condition is true. If the
condition turns out to be false, the looping
isn't obeyed and the program moves on to
the next statement.
Examples:
do {
betty++;
printf("%i",betty);
} while (betty<100);
#include <stdio.h>
main()
{
do
{
printf("Hello World!\n");
}while (1 == 1);
}
for
This sort of loop - runs from a
starting value to a finishing value
going up by one each time.
The for statement allows for a
controlled loop.
The counter does not have to be
incremented or (deremented) by 1;
we can use any value.
Syntax:
for( expression1 ; expression2 ;
expression3 ) statement... ;
OR
for ( counter=start_value; counter
<=
finish_value; ++counter )
compound statement;
Examples:
for(loop=0;loop<1000;loop++)
printf("%i\n",loop);
Prints numbers 0 through 999.
for(x=3, y=5; x<100+y; x++, y--)
{
printf("%i\n",x);
some_function();
}
Prints numbers 3 through 53.
some_function is called 51 times.
break
The break statement can only appear
in a switch body or a loop body. It
causes the execution of the current
enclosing switch or loop body to
terminate.
Syntax:
break;
Examples:
switch(henry)
{
case 1: print("Hi!\n");
break;
case 2: break;
}
If henry is equal to 2, nothing happens.
for(loop=0;loop<50;loop++)
{
if(loop==10)
break;
printf("%i\n",loop);
}
Only numbers 0 through 9 are
printed.
continue
The continue statement can only
appear in a loop body. It causes the
rest of the statement body in the
loop to be skipped.
Syntax:
continue;
continue Examples:
for(loop=0;loop<100;loop++)
{
if(loop==50)
continue;
printf("%i\n",loop);
}
The numbers 0 through 99 are
printed except for 50.
joe=0;
while(joe<1000) {
for(zip=0;zip<100;zip++) {
if(joe==500)
continue;
printf("%i\n",joe);
}
joe++;
}
Each number from 0 to 999 is printed
100 times except for the number 500
which is not printed at all.
goto
The goto statement transfers
program execution to some label
within the program.
Syntax:
goto label;
....
label:
goto Examples:
goto skip_point;
printf("This part was
skipped.\n"); skip_point:
printf("Hi there!\n");
Only the text "Hi there!" is printed.
return
The return statement causes the
current function to terminate. It can
return a value to the calling function.
A return statement can not appear in
a function whose return type is void.
If the value returned has a type
different from that of the function's
return type, then the value is
converted.
return Examples:
int alice(int x, int y)
{
if(x<y)
return(1);
else
return(0);
}
Functions
Every program in C has at least one
function which is main(). Unlike Pascal or
Basic, C does not provide procedures, it
uses functions to cater to both
requirements.
Functions are used to make a program
modular and to avoid repetition of
code. Any piece of code which is often
used in a program is a likely candidate for
being a function.
Syntax
In C a function has the following
structure :
<return type> function_name
(arguments list)
{
local variables;
code performing the necessary action;
}
#include <stdio.h>
void print_message()
{
printf("Inside print_message
function\n");
}
void main()
{
print_message(); // function call
printf("Back in the main program\n");
}
function call
In the above program, main() is the
entry point of the program, once
program execution begins, the control is
transferred to the print_message()
function. Inside the function it prints the
statement on the terminal and the
control returns to the main routine. After
the function call the program execution
will continue at the point where the
function call was executed.
return type
Note : If the return type of a function
is omitted, then the C compiler
assumes that the function will return
an integer. In case a function is
returning an integer value, it is a
good programming practise to
declare the return type instead
of omitting it. This improves the
readability of a program.
automatic variables
One point to remember is that
variables defined inside a function are
known as automatic variables since
they are automatically created each
time the function is called and are
destroyed once the function is
executed. Their values are local to the
function, they can be accessed only
inside the function in which they are
defined and not by other functions.
#include <stdio.h>
int square(number);
main()
{
int i; int result; i = 10; result = square(i);
printf ("Square of %d is %d\n", i, result);
}
int square(n) int n;
{
int temp; temp = n*n; return temp;
}
returning a value
When functions return a value to the
calling routine, a return() statement
needs to be used in the called
function. Also when the function is
declared we must declare the return
type. In the above program the value
returned by the function square is
stored in the variable result in the
calling program.
function call
One can call a function from
anywhere within a program. The
best use of functions is to organize a
program into distinct parts. The
function main() can only contain
calls to the various functions. The
actual work of the program is
performed in the functions following
main().
Function prototype
In C the function prototype has to be
declared before a function is used. A
function prototype is information to
the C compiler about the return
type of a function and the
parameter types that a function
expects. Usually all function prototypes
are declared at the start of a program.
Example:
Scope of Function
variables
variables defined inside a function
are known as automatic variables.
Their values are local to the
function, they can be accessed only
inside the function in which they are
defined and not by other
functions.
Local variables
Local variables are local to a
function. They are created everytime
a function is called and destroyed on
return from that function. These
variables cannot be accessed
outside a function.
Global variables
Global variables are declared outside
all functions. The value stored in
global variables is available to all
functions within a
program/application.
Static variables
Static variables are declared by
prefixing the keyword static to a
variable declaration. Unlike local
variables these are not destroyed on
return from a function, they continue
to exist and retain their value. These
variables can be accessed upon reentering a function.
Recursive functions
Recursive functions are functions calling
themselves repeatedly until a certain
condition is met. Recursion involves two
conditions. First the problem must be
written in a recursive form, and second,
the problem should have a loop
terminating statement. If the loop
terminating is missing, then the function
goes into an endless loop.
A most common example of a program
demonstrating recursion is calculation of
factorial of an interger number.
#include <stdio.h>
long int factorial(int n); /* function
prototype */
main () {
int num;
printf("Enter an integer value : ");
scanf("%d", &num);
printf("factorial of %d is %ld\n", num,
factorial(num)); } //end of main()
long int factorial(int n) {
if (n <= 1) return(1);
else return(n * factorial(n-1)); }
Declaration of arrays:
Like any other variable arrays must be
declared before they are used. The
general form of declaration is:
type variable-name[50];
The type specifies the type of the
elements that will be contained in the
array, such as int float or char and the
size indicates the maximum number of
elements that can be stored inside the
array for ex:
float height[50];
grades [100]=95;
for(i=0;i < 100;++i);
sum = sum + grades [i];
Will sequence through the first 100
elements of the array grades (elements
0 to 99) and will add the values of each
grade into sum. When the for loop is
finished, the variable sum will then
contain the total of first 100 values of
the grades array (Assuming sum were
set to zero before the loop was entered)
Initialisation of arrays
The initialisation of simple variables in
their declaration has already been
covered. An array can be initialised in a
similar manner. In this case the initial
values are given as a list enclosed in
curly brackets. For example initialising
an array to hold the first few prime
numbers could be written as follows:
int primes[] = {1, 2, 3, 5, 7, 11, 13};
Initialization of arrays:
We can initialize the elements in the
array in the same way as the ordinary
variables when they are declared. The
general form of initialization off arrays is:
type array_name[size]={list of
values};
The values in the list care separated by
commas, for example the statement
int number[3]={0,0,0};
Strings
A string is an array of characters.
Strings must have a 0 or null character
after the last character to show where
the string ends. The null character is
not included in the string.
There are 2 ways of using strings. The
first is with a character array and the
second is with a string pointer.
A character array is declared in the
same way as a normal array.
char ca[10];
String pointers
String pointers are declared as a
pointer to a char.
char *sp;
When you assign a value to the string
pointer it will automatically put the 0
in for you unlike character arrays.
char *sp;
sp = "Hello";
printf("%s",sp);
Multi dimensional
Arrays:
Elements of multi
dimension
arrays:
A 2 dimensional array marks [4][3] is
Initialization of
multidimensional arrays:
Like the one dimension arrays, 2
dimension arrays may be initialized by
following their declaration with a list of
initial values enclosed in braces
Example:
int table[2][3]={0,0,01,1,1};
Initializes the elements of first row to
zero and second row to 1. The
initialization is done row by row. The
above statement can be equivalently
written as :
int table[2][3]={{0,0,0},{1,1,1}}
. Structures
We already know that arrays are many
variables of the same type grouped together
under the same name. Structures are like
arrays except that they allow many
variables of different types grouped together
under the same name. For example you can
create a structure called person which is
made up of a string for the name and an
integer for the age. Here is how you would
create that person structure in C:
#include<stdio.h>
struct person
{
char *name;
int age;
};
int main()
{struct person p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}
Type definitions
#include<stdio.h>
typedef struct person
{
char *name;
int age;
} PERSON;
int main()
{PERSON p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}