Sei sulla pagina 1di 72

Introduction to C

Programming

Raghu H V
CDAC, Bangalore

8/17/2017 1
Computer
Device capable of performing computations and making
logical decisions
Computers process data under the control of sets of
instructions called computer programs

Hardware
Keyboard, screen, mouse, disks, memory, CD-ROM, and
processing units

Software
Programs that run on a computer

8/17/2017 2
Computer Organization
Input Unit

Output Unit

Main Memory

Arithmetic and Logic Unit(ALU)

Central Processing Unit (CPU)

Secondary Storage Unit

8/17/2017 3
8/17/2017 4
Machine Languages and Assembly
Languages
Three types of programming languages
1. Machine languages
Strings of numbers giving machine specific instructions
Example:
+1300042774
+1400593419
+1200274027
2. Assembly languages
English-like abbreviations representing elementary computer
operations (translated via assemblers)
Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

8/17/2017 5
High-level Languages

Three types of programming languages


(continued)
3. High-level languages
Codes similar to everyday English
Use mathematical notations (translated via compilers)
Example:
grossPay = basePay + overTimePay

8/17/2017
6
Translators
The source program is to be converted to the machine
language. A translator is required for such a translation.

Assemblers: translates the symbolic codes of programs of an


assembly language into machine language instructions.
Compilers: Compilers are the translators, which translate all the
instructions of the program into machine codes, which can be used
again and again. The entire program will be read by the compiler first
and generates the object code.
Interpreters: here each line is executed and object code is
provided.

8/17/2017 7
History of C
C language is a structure oriented programming language, was
developed at Bell Laboratories in 1972 by Dennis Ritchie.

C language features were derived from earlier language called B


(Basic Combined Programming Language BCPL).

C language was invented for implementing UNIX operating system.

In 1978, Dennis Ritchie and Brian Kernighan published the first


edition The C Programming Language.

In 1983, the American National Standards Institute (ANSI) established


a committee to provide a modern, comprehensive definition of C.
The resulting definition, the ANSI standard, or ANSI C.
8/17/2017 8
Structure oriented Object oriented Non structure

Large programs are divided into Programs are divided into There is no specific structure for
small programs called functions objects programming this language

Prime focus is on the data that


Prime focus is on functions and
is being operated and not on N/A
procedures that operate on data
the functions or procedures

Data moves freely around the


Data is hidden and cannot be
systems from one function to N/A
accessed by external functions
another

Program structure follows Top Program structure follows


N/A
Down Approach Bottom Up Approach

Examples:
BASIC, COBOL, FORTRAN
C, Pascal, ALGOL and Modula-2
8/17/2017
C++, JAVA and C# (C sharp) 9
Features
C language is not tied to any particular operating
system. It can be used to develop new operating
systems.

The C language is closely associated with the UNIX


operating system. The source code for the UNIX
operating system is in C.

The C programs are efficient, fast and highly portable,


i.e. C programs written on one computer can be run
on another with mere or almost no modification.

Because C is a hardware-independent.
8/17/2017 10
Structure of C program

8/17/2017 11
1 /*
2 A first program in C */ /* and */ indicate comments ignored by
3 #include <stdio.h> compiler
4 #include directive tells C to load a
5 /* function main begins program execution */ particular file
6 int main( void )
7 {
Left brace declares beginning of main
8 printf( "Welcome to C!\n" ); function
9 Statement tells C to perform an
10 action
return 0; /* indicate that program ended successfully */
return statement ends the
11
12 } /* end function main */ function
Welcome to C! Right brace declares end of main
function

C Programming is a structured and disciplined approach to program design

8/17/2017 12
A Simple C Program:
Printing a Line of Text
Comments
Text surrounded by /* and */ is ignored by computer.
Used to describe program.
#include<stdio.h>
Preprocessor directive
Tells computer to load contents of a certain file
<stdio.h> allows standard input/output operations

8/17/2017 13
Common Programming Error

1. Forgetting to terminate a comment with */.


2. Starting a comment with the characters */
or ending a comment with the characters /*.
3. Using a capital letter where a lowercase
letter should be used (for example, typing
Main instead of main).

8/17/2017 14
A Simple C Program: Printing a Line of Text
int main()
C programs contain one or more functions, exactly
one of which must be main
Parenthesis used to indicate a function
int means that main "returns" an integer value
Braces ({ and }) indicate a block
The bodies of all functions must be contained
in braces

8/17/2017 15
A Simple C Program:
Printing a Line of Text
Printf("Welcome to C!\n);
Instructs computer to perform an action
Specifically, prints the string of characters within quotes
(" ")
Entire line called a statement
All statements must end with a semicolon (;)
Escape character (\)
Indicates that printf should do something out of the
ordinary
\n is the newline character

8/17/2017 16
Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.


\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double-quote character in a string.

17
A Simple C Program:
Printing a Line of Text
return 0;
A way to exit a function
return 0, in this case, means that the program terminated
normally
Right brace }
Indicates end of main has been reached.

8/17/2017 18
8/17/2017 19
1 /*
2 Printing on one line with two printf statements */
3 #include <stdio.h> printf statement starts printing from
4 where the last statement ended, so the
5 /* function main begins program
text isexecution */one line.
printed on
6 int main( void )
7 {
8 printf( "Welcome " );
9 printf( "to C!\n" );
10
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */

Welcome to C!

8/17/2017 20
1 /*
2 Newline
Printing multiple lines with characters move the
a single printf */cursor to the
3 #include <stdio.h> next line
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome\nto\nC!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

Welcome
to
C!

8/17/2017 21
C Data Types
C data types are defined as the data storage
format that a variable can store a data to
perform a specific operation.
Data types are used to define a variable
before its use in a program.
Size of variable, constant and array are
determined by data types.

8/17/2017 22
Basic Data Types
int, char, float , double
Integer data type:
Integer data type allows a variable to store numeric
values.
int keyword is used to refer integer data type.
The storage size of int data type is 4 or 8 byte.
int (4 byte) can store values from -2,147,483,648 to
+2,147,483,647.
If you want to use the integer value that crosses the
above limit, you can go for long int and long long
int for which the limits are very high.
8/17/2017 23
Note
Integer data type:
We cant store decimal values using int data type.
If we use int data type to store decimal values, decimal values
will be truncated and we will get only whole number.
In this case, float data type can be used to store decimal values
in a variable.

8/17/2017 24
Basic Data Types
Character data type:
Character data type allows a variable to store only one character.
Storage size of character data type is 1. We can store only one
character using character data type.
char keyword is used to refer character data type.
For example, A can be stored using char datatype. You cant
store more than one character using char data type.

8/17/2017 25
Basic Data Types
Floating data type (float, double):
1. float:
Float data type allows a variable to store decimal values.
Storage size of float data type is 4.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float
data type.
2. double:
Double data type is also same as float data type which allows
up-to 10 digits after decimal.
The range for double data type is from 1E37 to 1E+37.

8/17/2017 26
sizeof() function in C
sizeof() function is used to find the memory space allocated
for each C data types.

8/17/2017 27
Modifiers in C
The amount of memory space to be allocated for a variable is
derived by modifiers.
Modifiers are prefixed with basic data types to modify (either
increase or decrease) the amount of storage space allocated to
a variable.
For example, storage space for int data type is 4 byte. We can
increase the range by using long int which is 8 byte. We can
decrease the range by using short int which is 2 byte.
There are 5 modifiers available in C language. They are,
short
long
signed
unsigned
long long
8/17/2017 28
Derived data type in C:
Array, pointer, structure and union are called derived data
type in C language.
Void data type in C:
Void is an empty data type that has no value.
This can be used in functions and pointers.

8/17/2017 29
C Tokens and Keywords
C tokens:
Each and every smallest individual units in a C program are
known as tokens.
C tokens are of six types. They are,
Keywords (eg: int, while),
Identifiers (eg: main, total, sum),
Constants (eg: 10, 20),
Strings (eg: total, hello),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)

8/17/2017 30
C Tokens Example
int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (Total = %d \n, total);
}
where,
main identifier
{,}, (,) delimiter
int keyword
x, y, total identifier
main, {, }, (, ), int, x, y, total tokens

8/17/2017 31
C Identifiers:
Each program elements in a C program are given a
name called identifiers.
Names given to identify Variables, functions and arrays
are examples for identifiers.

Rules for constructing identifier name in C:


First character should be an alphabet or underscore.
Succeeding characters might be digits or letter.
Punctuation and special characters arent allowed except
underscore.
Identifiers should not be keywords.

8/17/2017 32
C keywords:
Keywords are pre-defined words in a C compiler.
Each keyword is meant to perform a specific function in a C program.
Since keywords are referred names for compiler, they cant be used as
variable name.

Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

8/17/2017 33
C constants:
C constants are also like normal variables. But, only difference is, their
values cannot be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of C constant:
Integer constants
Real or Floating point constants
Octal & Hexadecimal constants
Character constants
String constants
Backslash character constants
8/17/2017 34
Example program using const keyword in C
#include <stdio.h>

void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = \\; /*special char const*/

printf(value of height : %d \n, height );


printf(value of number : %f \n, number );
printf(value of letter : %c \n, letter );
printf(value of letter_sequence : %s \n, letter_sequence);
printf(value of backslash_char : %c \n, backslash_char);
}
8/17/2017 35
Example program using #define directive
#include <stdio.h>

#define height 100


#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char \\'

void main()
{

printf("value of height : %d \n", height );


printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

}
8/17/2017 36
C variable:
C variable is a named location in a memory where a program
can manipulate the data. This location is used to hold the
value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int,
float, char etc.
Rules for naming C variable:
Variable name must begin with letter or underscore.
Variables are case sensitive
They can be constructed with digits, letters.
No special symbols are allowed other than underscore.
sum, height, _value are some examples for variable name
8/17/2017 37
Declaring & initializing C variable:
Variables should be declared in the C program before
its use.
Memory space is not allocated for a variable while
declaration. It happens only on variable definition.
Variable initialization means assigning a value to the
variable.

8/17/2017 38
There are three types of variables in C program
They are,
Local variable
Global variable
Environment variable
Example program for local variable in C:
The scope of local variables will be within the function
only.
These variables are declared within the function and
cant be accessed outside the function.

8/17/2017 39
Example program for global variable in C:
The scope of global variables will be throughout the program.
These variables can be accessed from anywhere in the program.
This variable is defined outside the main function. So that, this
variable is visible to main function and all other sub functions.
Environment variables in C:
Environment variable is a variable that will be available for all
C applications.
We can access these variables from anywhere in a C program
without declaring and initializing in an application.
The inbuilt functions which are used to access, modify and set
these environment variables are called environment functions.
There are 3 functions which are used to access, modify and assign
an environment variable in C. They are,
1. setenv()
2. getenv()
3. putenv()
8/17/2017 40
What is the output?
#include <stdio.h>

int main()
{
char ch = 'A';
char str*20+ = C Program";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;

printf("Character is %c \n", ch);


printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}

8/17/2017 41
Difference between variable declaration &
definition in C:

8/17/2017 42
Operators and Expressions
The symbols which are used to perform logical and
mathematical operations are called operators.

These operators join individual constants and


variables to form expressions.

Operators, functions, constants and variables are


combined together to form expressions.

Consider the expression A + B * 5. where, +, * are


operators, A, B are variables, 5 is constant and A + B *
5 is an expression.

8/17/2017 43
Operators and Expressions

8/17/2017 44
Arithmetic Operators
Arithmetic Algebraic
C opetration C expression
operator expression

Addition + f+7 f + 7
Subtraction pc p - c
Multiplication * bm b * m

Division / x
x y or or x y x / y
y

Remainder % r mod s r % s

8/17/2017 45
Precedence of Arithmetic Operators
Operator(s) Operation(s) Order of evaluation (precedence)
( ) Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost pair is
evaluated first. If there are several pairs of
parentheses on the same level (i.e., not nested),
they are evaluated left to right.
* Multiplication Evaluated second. If there are several, they are
/ Division evaluated left to right.
% Remainder
+ Addition Evaluated last. If there are several, they are
- Subtraction evaluated left to right.

8/17/2017 46
Equality and Relational Operators
Standard algebraic C equality or
Example of
equality operator or relational Meaning of C condition
C condition
relational operator operator

Equality operators
== x == y x is equal to y

!= x != y x is not equal to y
Relational operators

> x > y x is greater than y

< x < y x is less than y

>= x >= y x is greater than or equal to y

<= x <= y x is less than or equal to y

8/17/2017 47
1 /*
2 Addition program */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int integer1; /* first number to be input by user */
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
11
12 printf( "Enter first integer\n" ); /* prompt */
scanf obtains a value from the
13 scanf( "%d", &integer1 ); /* read an integer */ user and assigns it to
14 integer1
15 printf( "Enter second integer\n" ); /* prompt */
scanf obtains a value from the
16 scanf( "%d", &integer2 ); /* read an integer */
17 user and assigns it to
18 sum = integer1 + integer2; /* assign total to sum */ integer2
19
20 printf( "Sum is %d\n", sum ); /* print sum */
Assigns a value to
21 sum
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */

Enter first integer


45
Enter second integer
72
Sum is 117
8/17/2017 48
C Program: Adding Two Integers
Comments, #include<stdio.h> and main
int integer1, integer2, sum;
Declaration of variables
Variables: locations in memory where a value can be
stored
int means the variables can hold integers (-1, 3, 0, 47)
Variable names (identifiers)
integer1, integer2, sum
Identifiers: consist of letters, digits (cannot begin with
a digit) and underscores( _ )
Case sensitive
Definitions appear before executable statements
If an executable statement references an undeclared
variable it will produce a syntax (compiler) error

8/17/2017 49
Good Programming Practice
Choosing meaningful variable names helps make a
program self-documenting, i.e., fewer comments are
needed.
Multiple-word variable names can help make a
program more readable. Avoid running the separate
words together as in totalcommissions. Rather,
separate the words with underscores as in
total_commissions, or, if you do wish to run the
words together, begin each word after the first with a
capital letter as in totalCommissions.

8/17/2017 50
C Program: Adding Two Integers

Scanf("%d", &integer1);
Obtains a value from the user
scanf uses standard input (usually keyboard)
This scanf statement has two arguments
%d - indicates data should be a decimal integer.
&integer1 - location in memory to store variable.
& holds the address of the variable.
When executing the program the user responds to
the scanf statement by typing in a number, then
pressing the enter (return) key

8/17/2017 51
Assignment Operators
Assignment operators abbreviate assignment expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment operator
Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)

8/17/2017 52
Assignment Sample
Explanation Assigns
operator expression
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 C = c + 7 ???
-= d -= 4 D = d - 4 ???
*= e *= 5 E = e * 5 ???
/= f /= 3 F = f / 3 ???
%= g %= 9 G = g % 9 ???

Arithmetic assignment operators.

53
Increment and Decrement Operators

Increment operator (++)


Can be used instead of c+=1
Decrement operator (--)
Can be used instead of c-=1
Pre increment
Operator is used before the variable (++c or --c)
Variable is changed before the expression is evaluated
Post increment
Operator is used after the variable (c++ or c--)
Expression executes before the variable is changed

8/17/2017 54
Increment and Decrement Operators
If c equals 5, then
printf( "%d", ++c );
Prints 6
printf( "%d", c++ );
Prints 5
In either case, c now has the value of 6
When variable not in an expression
Pre incrementing and post incrementing have the same
effect
++c;
printf( %d, c );
Has the same effect as
c++;
printf( %d, c );
8/17/2017 55
Operator Sample expression Explanation

++ ++a Increment a by 1, then use the new value of a in the


expression in which a resides.
++ a++ Use the current value of a in the expression in which a
resides, then increment a by 1.
-- --b Decrement b by 1, then use the new value of b in the
expression in which b resides.
-- b-- Use the current value of b in the expression in which b
resides, then decrement b by 1.

Increment and decrement operators.


56
1 /*
2 Preincrementing and postincrementing */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int c; /* define variable */
9
10 /* demonstrate postincrement */
11 c = 5; /* assign 5 to c */
12 printf( "%d\n", c ); /* print 5 */
13 printf( "%d\n", c++ ); /* print 5 then postincrement */
14 printf( "%d\n\n", c ); /* print 6 */ c is printed, then
15
incremented
16 /* demonstrate preincrement */
17 c = 5; /* assign 5 to c */
18 printf( "%d\n", c ); /* print 5 */
19 printf( "%d\n", ++c ); /* preincrement then print 6 */
20 printf( "%d\n", c ); /* print 6 */ c is incremented, then
21
22 return 0; /* indicate program ended successfully */
printed
23

24 } /* end function main */

57
8/17/2017
C Program: Adding Two Integers
= (assignment operator)
Assigns a value to a variable
Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
Variable receiving value on left
Printf("Sum is %d\n,sum);
Similar to scanf
%d means decimal integer will be printed
sum specifies what integer will be printed
Calculations can be performed inside printf statements
printf( "Sum is %d\n", integer1 + integer2 );

8/17/2017 58
Common Programming Errors
A calculation in an assignment statement must be on the right
side of the = operator. It is a syntax error to place a calculation on
the left side of an assignment operator.
Forgetting one or both of the double quotes surrounding the
format control string in a printf or scanf.
Forgetting the % in a conversion specification in the format
control string of a printf or scanf.
Placing an escape sequence such as \n outside the format
control string of a printf or scanf.
Not providing a conversion specifier when one is needed in a
printf format control string to print the value of an expression.

8/17/2017 59
Decision Control Statements
In decision control statements, group of statements are
executed when condition is true. If condition is false, then else
part statements are executed.
There are 3 types of decision making control statements in C
language. They are,
if statements
if else statements
nested if statements

8/17/2017 60
Decision Control Statements

8/17/2017 61
Loop Control Statements
Loop control statements are used to perform looping
operations until the given condition is true. Control comes out
of the loop statements once condition becomes false.
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They
are,
for
while
do-while

8/17/2017 62
Loop Control Statements

8/17/2017 63
Case Control Statements
The statements which are used to execute only specific block
of statements in a series of blocks are called case control
statements.
There are 4 types of case control statements in C language.
They are,
switch
break
continue
goto

8/17/2017 64
Switch Case Statement
Switch case statements are used to execute only specific
case statements based on the switch expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}

8/17/2017 65
Calculator program using switch
#include <stdio.h>
#include <stdlib.h>
int main()
{
char operator;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&operator);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(operator)
{
case '+: printf("num1+num2=%.2f",num1+num2); break;
case '-: printf("num1-num2=%.2f",num1-num2); break;
case '*: printf("num1*num2=%.2f",num1*num2); break;
case '/: printf("num2/num1 = %.2f",num1/num2); break;
default: printf("Error! operator is not correct"); break;
}
return 0;
}
8/17/2017 66
Break and Continue Statement
break statement:
Break statement is used to terminate the while loops,
switch case loops and for loops from the subsequent
execution.
Syntax: break;
Continue statement in C:
Continue statement is used to continue the next
iteration of for loop, while loop and do-while
loops. So, the remaining statements are skipped
within the loop for that particular iteration.
Syntax : continue;

8/17/2017 67
goto Statement
goto statements is used to transfer the normal flow
of a program to the specified label in the program.
Below is the syntax for goto statement in C.
{
.
goto label;
.
.
LABEL:
statements;
}
8/17/2017 68
Storage Class specifiers
Storage class specifiers in C language tells the compiler where to
store a variable, how to store the variable, what is the initial value
of the variable and life time of the variable.
Syntax: storage_specifier data_type variable _name
Types of Storage Class Specifiers in C:
There are 4 storage class specifiers available in C language. They are,
auto
extern
static
register

8/17/2017 69
Storage Class specifiers

8/17/2017 70
For faster access of a variable, it is better to go for
register specifiers rather than auto specifiers.
Because, register variables are stored in register
memory whereas auto variables are stored in
main CPU memory.
Only few variables can be stored in register
memory. So, we can use variables as register that
are used very often in a C program.

8/17/2017 71
8/17/2017 72

Potrebbero piacerti anche