You are on page 1of 64

Introduction to c

 C is a general-purpose computer
programming language
 Combines the features of a high level
language with it's ability to access low level
commands– so suitable for System Sw &
appln sw development
 The C programming language was designed
by Dennis Ritchie at Bell Laboratories in the
early 1970s
 Specially Designed for systems programming
◦ Operating systems
◦ Utility programs
◦ Compilers
 Evolved from B, which evolved from BCPL
 Influenced by
◦ ALGOL 60 (1960),
◦ CPL (Cambridge, 1963),
◦ BCPL (Martin Richard, 1967),
◦ B (Ken Thompson, 1970)
 The rapid growth of C led to development of
different versions similar but often
incompatible.
 So in 1983 a committee was formed by ANSI
to define a standard for C
 Standardized in 1989 by ANSI (American
National Standards Institute) known as ANSI C
 Structured language
 Uses features of High-level language
 Handle bit-level operations
 Supports a variety of data types & operators
 Supports dynamic memory mgt
 Extends itself by addition of functions to its
library
#include<stdio.h>
main()
{
/* the following st displays welcome to c */
printf(“welcome to C”);
}
 The files that are specified in the include
section is called as header file
 These are precompiled files that has some
functions defined in them
 We can call those functions in our program by
supplying parameters
 Header file is given an extension .h
 C Source file is given an extension .c
 This is the entry point of a program
 When a file is executed, the start point is the
main function
 From main function the flow goes as per the
programmers choice.
 There may or may not be other functions
written by user in a program
 Main function is compulsory for any c
program
C permits the following form of main fn
 main()
 int main()
 void main()
 main(void)
 void main(void)
 int main(void)
 comment
/*….
…….*/
This can span over to multiple lines
 A character denotes any alphabet ,digit or symbols to
represent information. The following are the valid
alphabets, numbers and special symbols permitted in
C
 Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
 Alphabets: a, b, ….z
A, B, ……...Z
 Special Characters:

( ) { } [ ] < > = ! $ ? . , : ; ‘ “ & | ^ ~ ` # \ blank - _ / *


%@
 "Keywords" are words that have special
meaning to the C compiler
 identifier is the fancy term used to mean
‘name’.
 In C, identifiers are used to refer to a number
of things: we've already seen them used to
name variables and functions.
 Should not be a reserved word like int etc..
 Should start with a letter or an underscore(_)
 Can contain letters, numbers or underscore.
 No other special characters are allowed
including space
 Variable names are case sensitive
◦ A and a are different.
 Declaring Variable as Constant
 The values of some variable may be required to remain constant through-out
the program. We can do this by using the qualifier const at the time of
initialization.

Example:

Const int class_size = 40;

The const data type qualifier tells the compiler that the value of the int
variable class_size may not be modified in the program.
 Integer Constants.
◦ e.g. 426
◦ +756
◦ +756
◦ 588 etc.
 Character Constants.
◦ e.g.
◦ ‘ E’
◦ ‘h ’
◦ ‘8 ’
 Real Constant
 String constants
 Backslash character constants
 A variable is data name that may be used to
store data value
 Takes different values at times during
execution
 Declaration
<<Data type>> <<variable name>>;
int a;
<<varname>>=<<value>>;
a=10;
 Usage
<<varname>>
a=a+1; //increments the value of a by 1
 Primary data types
◦ int, float, char,void
 Derived data types
◦ Arrays come under this category
◦ Arrays can contain collection of int or float or char
or double data
 User defined data types
◦ Structures and enum fall under this category.
 C has special shorthand that simplifies
coding of certain type of assignment
statements.
 Example
 a = a + 2; can be written as a + =2;
 This shorthand works for all binary
operators in C.
 General form:
 <variable> < operator> =
<variable/constant/expression>
 Formatted Input For Scanf:
 The formatted input refers to input data that has been arranged in a particular
format. Input values are generally taken by using the scanf function. The scanf
function has the general form.
Scanf (“control string”, arg1, arg2, arg3 ………….argn);
 The format field is specified by the control string and the arguments
arg1, arg2, …………….argn specifies the address of location where address is to
be stored.
The control string specifies the field format which includes format specifications
and optional number specifying field width and the conversion character % and
also blanks, tabs and newlines.
The Blanks tabs and newlines are ignored by compiler. The conversion character %
is followed by the type of data that is to be assigned to variable of the assignment.
The field width specifier is optional.
 Formatted Input - Scanf:
 The general format for reading a integer number is
%xd
Here percent sign (%) denotes that a specifier for
conversion follows and x is an integer number which
specifies the width of the field of the number that is
being read. The data type character d indicates that
the number should be read in integer mode.
 Example :

scanf (“%4d %4d”, &sum1, &sum2);
 Output
◦ printf(“%d”,a)
◦ Prints the value present in variable a on the screen
 Code Format
---- ------
%c character
%d signed integers
%e scientific notation, with a lowercase "e"
%E scientific notation, with a uppercase "E"
%f floating point
%g use %e or %f, whichever is shorter
%G use %E or %f, whichever is shorter
%o octal
%s a string of characters
%u unsigned integer
%x unsigned hexadecimal, with lowercase letters
%X unsigned hexadecimal, with uppercase letters
 Reading a character
◦ getchar () ; The given value is displayed on the
screen and the compiler wait for another character
to be typed
◦ getch() reads a single character directly from the
keyboard, without echoing to the screen.
◦ getche() is used to get a character from console,
and echoes to the screen
 Reading a character
 # include < stdio.h >
void main (
{
char C;
printf (“Type one character:”) ;
C = getchar () ;
Printf (” The character you typed is = %c”, C) ;
}
 writing a character
 The putchar function which in analogus to
getchar function can be used for writing
characters one at a time to the output
terminal. The general form is

putchar (variable name);


 An operator is a symbol which helps the user to
command the computer to do a certain
mathematical or logical manipulations.
 C has a rich set of operators which can be
classified as
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
 ++
 --
 Types
◦ Postfix
 Ex a++, a--
◦ Prefix
 Ex - - a, ++a
 Conditional Operator (?:) is ternary operator and is used in
certain situations, replacing if-else condition phrases.
Conditional operator’s shape is:
Condition_phrase ? phrase1 : phrase2;
If conditional_phrase is true, phrase1 is executed and whole
phrase is assigned with value of this phrase1. If the
conditional phrase is false, then phrase2 is executed, and
whole phrase is assigned with phrase2 value.

int a, b, c;
...
c = a > b ? a : b; // if a>b "execute" a, else b
 Evaluation of Expressions
 Expressions are evaluated using an assignment
statement of the form
Variable = expression;

Example of evaluation statements are



x=a*b–c
y=b/c*a
z = a – b / c + d;
 First parenthesized sub expression left to right are
evaluated.
 If parenthesis are nested, the evaluation begins with
the innermost sub expression.
 The priority rule is applied in determining the order
of application of operators in evaluating sub
expressions.
 The associtivity rule is applied when two or more
operators of the same precedence level appear in the
sub expression.
 Arithmetic expressions are evaluated from left to
right using the rules of precedence.
 When Parenthesis are used, the expressions within
parenthesis assume highest priority.
 Implicit type conversion
◦ C automatically converts any intermediate values to the
proper type. This automatic type conversion is known as
implicit type conversion
 Explicit type conversion
◦ Many times there may arise a situation where we want to
force a type conversion in a way that is different from
automatic conversion.
Consider for example the calculation of number of
female and male students in a class
female_students
Ratio = -------------------
male_students
 C possesses decision making capability by
supporting the following sts
◦ If
◦ Switch
◦ goto
if
if (condition)
{
stmt 1; //Executes if Condition is true
}
Exmple
If(no<0)
{
Printf(“-ve”);
Exit; //stop execution
}
If –else
if (condition)
{
stmt 1; //Executes if Condition is true
}
else
{
stmt 2; //Executes if condition is false
}
Nested if exmple
switch(var)
{
case 1: /*if var=1 this case executes */
stmt;
break;
case 2: /*if var=2 this case executes */
stmt;
break;
default: /*if var is something else this will
execute*/
stmt;
}
example
• Rules for switch st
• Switch expression must be an integral type
• Case labels must be constant or constant expression
• Case labels must be unique
• Case labels must end with colon
• Break st transfer the control out of switch
• Break is optional – what happens if no break st
• Default is optional – executed when the expression don’t
find matching case label
• There can be atmost one default label
• Nesting is permitted
 Useful for 2 way decision
 Take 3 operands
 Known as conditional/ternary operator
 Format
◦ Conditional exp ? Exp1 : exp2
 Conditional exp evaluated first. If result is
nonzero/true exp1 is evaluated and its value
is returned or if result is zero/false exp2 is
evaluated and its value is returned
 A common feature of any programming
script/language is, its ability to perform
repeat tasks until a condition is satisfied,
and, its ability to take decision.
 During looping a set of statements are
executed until some conditions for
termination of the loop is encountered.
 A program loop therefore consists of two
segments one known as body of the loop and
other is the control statement
 The control statement tests certain conditions
and then directs the repeated execution of
the statements contained in the body of the
loop.
 In looping process in general would include
the following four steps
1. Setting and initialization of a counter
2. Execution of the statements in the loop
3. Incrementing the counter
 4. Test for a specified conditions for the
execution of the loop
 The test may be either to determine whether
the loop has repeated the specified number
of times or to determine whether the
particular condition has been met.
 The syntax of for loop is
for(initialisation;condition checking;increment)
{
set of statements
}
Eg: Program to print Hello 10 times
for(I=0;I<10;I++)
{
printf(“Hello”);
}
 The syntax for while loop
while(condn)
{
statements;
}
Eg:
a=10;
while(a != 0) Output:
10987654321
{
printf(“%d”,a);
a--;
}
 The syntax of do while loop
do
{
set of statements
}while(condn);

Eg:
i=10; Output:
do 10987654321
{
printf(“%d”,i);
i--;
}while(i!=0)
 C language permits to jump out of the loop.
 The break statement allows us to accomplish
this task.
 It provides an early exit from for, while, do
and switch constructs.
 A break causes the innermost enclosing loop
or switch to be exited immediately.
 Format is break;
 During loop operations it may be necessary
to skip a part of the body of the loop under
certain conditions. Like the break statement C
supports similar statement called continue
statement.
 It causes the loop to be continued with the
next iteration after skipping any statement in
between.
 the format of the continue statement is
simply
◦ continue;
 Write a program
that finds the sum
of five positive
integers. If a
negative number is
entered, the sum
should not be
performed
 Example
 The goto statement is a jump statement which
jumps from one point to another point within a
function.
 The goto statement is marked by label statement.
Label statement can be used anywhere in the
function above or below the goto statement.
 Example
 Avoiding goto
◦ It generates less efficient code
◦ Careful program design can usually avoid use of goto
◦ Many of goto will make the program logic complicated
and less readable
◦ In case any goto is absolutely necessary, it should be
properly documented
 Just as you can break out of a loop, you can
break out of a program by using the standard
library function exit().
 This function causes immediate termination
of the entire program, forcing a return to the
operating system. In effect, the exit() function
acts as if it were breaking out of the entire
program.
 The general form of the exit() function is:
void exit(int return_code);

You might also like