module 1_part 2 (1)
module 1_part 2 (1)
APTER-2
INTRODUCTION TO C LANGUAGE
C
H
Introduction to C
C was evolved from ALGOL,BCPL, and B by Dennis Ritchie at the Bell laboratories.
C is a general-purpose programming language developed by Dennis Ritchie at AT&T
Bell laboratories in 1972.
Advantages/Features /Characteristics of C Language
C language is very popular language because of the following features:
1. C is highly portable, which means program written for one computer can be run on
another with little or no modification.
2. C is structured Programming Language as the code can be organized as a
collection of one or more functions.
3. It is considered a high-level language because it allows the programmer to solve a
problem without worrying about machine details.
4. It has wide variety of operators using which a program can be written easily to solve
a given problem.
5. C is more efficient which increases the speed of execution and management of
memory compared to low level languages.
6. C is machine independent. The program written on one machine will work on
another machine.
7. C can be executed on many different hardware platforms.
Page 1
C Programming for Problem Solving Module1
1
White spaces
Sy Name Sym Name Sym Name
mb Bol bol
~ Tilde | [ Left bracket
Vertical bar
# Hash ( Left ] Right bracket
parenthesis
$ Dollar sign ) Right : Colon
parenthesis
% Percent _ Underscore ” Quotation
Sign mark
^ Caret + Plus sign ; Semicolon
Comments/Documentation Section
Comments are short explaining the purpose of the program or a statement.
They are non executable statements which are ignored by the compiler.
The comment begins with /* and ends with */.
The symbols /* and */ are called comment line delimiters.
We can put any message we want in the comments.
Example: /* Program to compute Quadratic Equation */
Note: Comments are ignored by C compiler, i.e. everything within comment delimiters
Page 2
C Programming for Problem Solving Module1
1
Preprocessor Directives
Preprocessor Directives begins with a # symbol
Provides instructions to the compiler to include some of the files before compilation
starts.
Some examples of header files are
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
#include<stdlib.h> Etc…
Page 3
C Programming for Problem Solving Module1
1
Subroutine Section: All user defined functions that are called in main function should be
defined.
1.3 Algorithm
It is a step by step procedure to solve a problem
A sequential solution of any problem that is written in natural language.
Using the algorithm, the programmer then writes the actual program.
The main use of algorithm is to help us to translate English into C.
It is an outline or basic structure or logic of the problem.
Characteristics of Algorithm
Each and every instruction must be precise and unambiguous
Each instruction execution time should be finite.
There should be a termination condition.
It has to accept 0 or more inputs and produce compulsory an output.
It can accept any type of input and produce a corresponding output.
General Way of Writing the Algorithm
Name of the algorithm must be specified.
Beginning of algorithm must be specified as Start
Input and output description may be included
Step number has to be included for identification
Each step may have explanatory note provided with in square bracket followed by
operation.
Completion of algorithm must be specified as end or Stop.
Page 4
C Programming for Problem Solving Module1
1
Page 5
C Programming for Problem Solving Module1
1
Ex 1.Algorithm and Flowchart to Input the dimensions of a rectangle and print its area
Step 1: Start
Step 2: [input the values of length
and breadth]
read length, breadth
Step 3: [Compute ‘area’]
area=length * breadth
Step 4: display area
Step 5: Stop
Page 6
C Programming for Problem Solving Module1
1
1.4 C Tokens
C Tokens
strings
Page 7
C Programming for Problem Solving Module1
1
1.4.1 Keywords
The tokens which have predefined meaning in C language are called keywords.
They are reserved for specific purpose in C language they are called as Reserved
Words.
There are totally 32 keywords supported in C they are:
auto Double if static
break Else int struct
case Enum long switch
char Extern near typedef
const Float register union
continue For return unsigned
default Volatile short void
do Goto signed while
Rules for keywords
1. Keywords should not be used as variables ,function names, array names etc.
2. All keywords should be written in lowercase letters.
3. Keywords meaning cannot be changed by the users.
1.4.2 Identifiers
Definition:
Identifiers are the names given to program elements such as variables, constants
,function names, array names etc
It consists of one or more letters or digits or underscore.
Rules for identifiers
1. The First character should be an alphabet or an underscore _
Then First character is followed by any number of letters or digits.
2. No extra symbols are allowed other than letters ,digits and Underscore
3. Keywords cannot be used as an identifier
4. The length can be 31 characters for external, 63 for internal.
5. Identifiers are case sensitive.
Example: Area, Sum_
Ex:-
Identifier Reasons for invalidity
india06 Valid
_india Valid
india_06 Valid
india_06_king Valid
Page 8
C Programming for Problem Solving Module1
1
1.2.3 Constants
Definition: Constants refers to fixed values that do not change
during the execution of a program.
Page 9
C Programming for Problem Solving Module1
1
Page 10
C Programming for Problem Solving Module1
1
\\ Backslash Backslash
\0 NULL
Page 12
C Programming for Problem Solving Module1
1
Using variable name ,data can be stored in a memory location and can be accessed or
manipulated very easily.
A variable may take different values during the execution of the program.
A variable name can be chosen by a programmer in a meaningfull way.
Rules for variables
The First character should be an letter(alphabet or an underscore _ )
Then First character is followed by any number of letters or digits.
No extra symbols are allowed other than letters ,digits and Underscore
Keywords cannot be used as an identifier
Case sensitive
White space is not allowed
Example:
Variables Valid /invalid Reason
Sum valid
For1 valid
distance valid
Sum1 valid
For invalid (it is a keyword)
123 invalid Cannot start with a digit
Declaration of variables:
Giving a name to memory location is called declaring a variable.
Reserving the required memory space to store the data is called defining a variable.
General Syntax of variable declaration :
datatype variable;
Example: int a; Syntax
double ratio;
datatype variable1, variable2,… ..... variable n;
Example: float x, y;
From the above examples “a” is a variable of type integer and allocates 2 bytes of
memory. “
x” and “y” are two variable of type float which will be allocated 4 bytes of memory for
each variable.
“ratio” is a double data type variables which will be allocated with 8 bytes of memory
for each.
Variable Initialization/Assigning values to variables
Variables are not initialized when they are declared and defined, they contain garbage
values(meaningless values)
The method of giving initial values for variables before they are processed is called
variable initialization.
Page 13
C Programming for Problem Solving Module1
1
General Syntax:
Variable_name = constant;
Variable_name = expr;
Where,
Var_name is the name of the variable given by the programmer ,
expr is the value of the expression.
The “expr” on the right hand side is evaluated and stored in the variable name (Var_name) on left
hand side.
The expression on the right hand side may be a constant, variable or simple expressions . Examples:
int a=10; // assigns the value 10 to the integer variable a
float x; // creates a variable y of float type and assigns value 20 to it.
x=20;
price = cost*3; //assigns the product of cost and 3 to price.
sum=sum+2; // assigns the sum +2 value to sum variable
Output Function : To print the value on the screen or to store the value on the file, the output
functions are used. printf() is the function which is use to display the output on the screen.
The General format of the printf() function is
printf(“control string”,variable1,variable2,…..);
Example
Formatted Output of Integer :Similar to formatted input , there is a formatted output also to have the
output in a format manner.
In this control string consists of three types of items.
Characters that will be printed on the screen as they appear
Format specification that define the output format for display of each item
Escape sequence characters such as
\n – new line
C Programming for Problem Solving Module1
1
\b – back space
\f – form feed
\r – carriage return
\t - horizontal tab
\v – vertical tab
The format speciation is as follows
%wd
Where w – is the field width of the number to be write . d will indicates as data type in
integer number.
Examples:
Printf(“%d”,9876); // output:
9876
printf(“%6d”,19876);
output:
1 2 3 4 5 6
1 9 8 7 6
printf(“%-6d”,9876);
output:
1 2 3 4 5 6
9 8 7 6
printf(“%06d”,9876);
output:
1 2 3 4 5 6
0 0 9 8 7 6
Example
scanf(“%2.1f %5.2f”,&num1,&num2);
data line is 50.1 31425.20
printf(“%7.2f ”,y);
output:
1 2 3 4 5 6 7
9 8 . 7 6
printf(“%-7.2f ”,y);
output:
1 2 3 4 5 6 7
9 8 . 7 6
Example:
Char name;
Scanf(“%c”, &name); \\ I / P : a
Char name[20];
Scanf(“%s”,&name); \\ I / P : sathyabama
where,
%s – A sequence of characters can be displayed.
%c – A single character can be displayed.
The character will be displayed right-justified in the field of w, left-justified by placing
a minus sign before the integer w.
Example:
Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);
Output:
1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20
a N I l k U m A R g u p t A
Printf(“%-20.10s”, name);
Output:
1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20
A N I l K U m A r
C Programming for Problem Solving Module1
1
getchar() –
putchar() –
getch() –
putch() –
gets() –
puts()
getchar()
This function reads a character-type data from standard input.
• It reads one character at a time till the user presses the enter key.
Example: char c; c = getchar();
Syntax Variable-name = getchar
#include
void main()
{
char c;
printf(“enter a character”);
c=getchar();
printf(“c = %c ”,c);
}
putchar()
This function prints one character on the screen at a time which is read by standard input.
Example: char c= ‘c’; putchar (c);
#include
void main()
{ char ch;
printf(“enter a character: ”);
scanf(“%c”, ch);
putchar(ch);
}
getch() & getche()
These functions read any alphanumeric character from the standard input device
The character entered is not displayed by the getch() function until enter is pressed
C Programming for Problem Solving Module1
1
putch()
This function prints any alphanumeric character taken by the standard input device Example:
#include
void main()
{
char ch;
printf(“Press any key to continue”);
ch = getch(); printf(“ you pressed:”);
putch(ch);
}
gets() String I/O
This function is used for accepting any string until enter key is pressed (string will be covered later) Syntax char
str[length of string in number];
gets(str);
#include
void main()
{
char ch[30];
puts()
This function prints the string or character array. It is opposite to gets()
Syntax char str[length of string in number]; gets(str); puts(str);
Symbols Meaning
%c Character
%o octal number
%s String
%lf Double
Page 23