C Unit 1
C Unit 1
STRUCTURE OF A C PROGRAM
In general, a structure of C program is composed of the following sections:
Documentation Section
Pre-processor directives
Documentation Section:
Function Section
This section is compulsory. This section can have one or more functions. Every program written in C
language must contain main () function.
The execution of every C program always begins with the function main ().
The body of the function consists of a set of statements enclosed within curly brackets commonly
known as braces.
The statements are of two types.
Declaration Part:
These are declaration statements, which declares the entire variables used. Variable initialization is
also coming under these statements.
E.g. C Program
Line1 is a comment; Line 2 is a preprocessor directive. Line3 is a header of the function main. Line 4, 5, 6
form the body of main function.
Example Program:
/*Addition of two numbers*/ Documentation Section
#include<stdio.h> Pre-processor directives
#define A 10 Definition Section
int c; Global declarations
int sum(int,int);
main() Main() functions
{
int b;
printf(“Emter the value for B:”);
scanf(“%d”,&b); Execution Part
c=sum(b);
printf(“\n Answer=%d”,c);
getch();
}
int sum(int y)
{
c=A+Y; Sub Program
return(c);
}
PROGRAMMING RULES
1. All statements should be written in lower case letters.
2. Upper case letters are only used for symbolic constants.
3. Blank spaces cannot be used while declaring a variable, keyword, constant and function.
4. The programmer can write the statement anywhere between the two braces following the declaration
part.
5. The user can also write one or more statements in one line by separating semicolon (;).
Ex:
a=b+c;
d=b*c;
or
a=b+c; d=b*c;
The opening and closing braces should be balanced. For example, if opening braces are four, then closing
braces should also be four.
Type Modifier:
Type modifier is used to alter their range and storage space to fit for various requirements. Type qualifiers
are
short
long
signed
unsigned
Pointer Pointer is a variable which stores the address of the another variable.
STORAGE CLASS:
Storage classes are used to define scope and life time of a variable. There are four storage classes in C
programming.
auto
extern
static
register
Storage Storage Default Scope Life-time
Classes Place Value
Example: # include<stdio.h>
void main()
{
register int a=200;
printf(“a=%d”,a);
}
Output:
a=200
Example:
#INCLUDE<STDIO.H>
extern int v=10;
void call1()
void main()
{ call1();
printf(“In main v=%d”,v);
}
void call1()
{ printf(“In call1() v=%d”,v);
}
Output:
In main v=10
In call1( ) v=10
Since v is a external variable it is visible and accessed in all functions.
Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating point number,
character or a string.
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant
Qualified constants:
Qualified constants are created by using const qualifier. E.g. const char a = “A‟ The usage of const
qualifier places a lock on the variable after placing the value in it. So we can’t change the value of the
variable a
Symbolic constants
Symbolic constants are created with the help of the define pre-processor directive. For ex #define
PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant is replaced by its
actual value during the pre-processing stage.
2) C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data
type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}
Output:
3.140000
Enumeration Constants:
An enumeration is a user-defined data type or constant. Enumeration is achieved by using the
keyword enum.
The enumeration type is an integral data type.
SYNTAX:
enum enum_name{ const1,const2, ... constN };
It is start with 0 (zero) by default and value is incremented by 1for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.
Example:
#include <stdio.h>
main()
{
enum Day{ Monday =1, Tuesday, Wednesday, Thursday};
enum { A= 3, B , C , Z = 400, X, Y };
printf("Wednesday = %d\n", Wednesday);
printf("B = %d \t C = %d\n", B,C);
printf("X = %d \t Y = %d\n", X,Y);
printf("Thursday/Tuesday = %d\n", Thursday/Tuesday);
}
Keywords:
Keyword is a reserved word that has a particular meaning in the programming language. The
meaning of a keyword is predefined. It can‟t be used as an identifier
Operands
An operand specifies an entity on which an operation is to be performed. It can be a variable name, a
constant, a function call.
E.g: a=2+3 Here a, 2 & 3 are operands
Operator
An operator is a symbol that is used to perform specific mathematical or logical manipulations.
For e.g, a=2+3 Here = & + are the operators
Precedence of operators
The precedence rule is used to determine the order of application of operators in evaluating sub expressions.
Each operator in C has a precedence associated with it.
The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence in the sub
expression.
An operator can be left-to-right associative or right-to-left associative.
Classification of Operators
The operators in C are classified on the basis of
The number of operands on which an operator operates
The role of an operator
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator
Binary Operator: A binary operator operates on two operands. Some of the binary operators are,
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Division
&& Logical AND
Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary operator.
Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction, multiplication, division etc.
output
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1
Increment operator
The operator ++ adds one to its operand.
++a or a++ is equivalent to a=a+1
Prefix increment (++a) operator will increment the variable BEFORE the expression is evaluated.
Postfix increment operator (a++) will increment AFTER the expression evaluation.
E.g.
c=++a. Assume a=2 so c=3 because the value of a is incremented and then it is assigned to c.
d=b++ Assume b=2 so d=2 because the value of b is assigned to d before it is incremented.
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
Prefix decrement (--a) operator will decrement the variable BEFORE the expression is evaluated.
Postfix decrement operator (a--) will decrement AFTER the expression evaluation.
2. Relational Operators
Relational operators are used to compare two operands. There are 6 relational operators in C, they are
If the relation is true, it returns value 1 and if the relation is false, it returns value 0.
An expression that involves a relational operator is called as a condition. For e.g a<b is a condition.
Sample program
#include<stdio.h>
main()
{
int a=10, b=5;
printf(“a>b is %d, a>b);
printf(“a>=b is %d, a>=b);
printf(“a<b is %d, a<b);
printf(“a<=b is %d, a<=b);
printf(“a==b is %d, a==b);
printf(“a!=b is %d, a!=b);
}
Output
a>b is 1
a>=b is 1
a<b is 0
a<=b is 0
a==b is 0
a!=b is 1
3. Logical Operators
Logical operators are used to logically relate the sub-expressions. There are 3 logical operators in C,
they are
If the relation is true, it returns value 1 and if the relation is false, it returns value 0 .
Logial If c=5 and d=2 then,((c==5) && It returns true when both
&& AND (d>5)) returns false. conditions are true
If c=5 and d=2
It returns true when at-least
Logical then, ((c==5) || (d>5)) returns
one of the condition is true
|| OR true.
Logical If c=5 then, !(c==5) returns It reverses the state of the
! NOT false. operand
Output
logical AND is 1
logical OR is 1
logical NOT is 0
4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the individual
bits of the operands. They are used for bit manipulation.
E.g.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
5. Assignment Operators
To assign a value to the variable assignment operator is used.
6.Conditional Operator
It is the only ternary operator available in C.
Conditional operator takes three operands and consists of two symbols ? and : .
Conditional operators are used for decision making in C.
Syntax :
(Condition? true_value: false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Output
The option1=8
The option2=10
7.Miscellaneous/Special Operators
Other operators available in C are
() Function Call Operator Used in functions
[] Array subscript Operator Used in declaring an array
Direct member access operator Used to access a member of a struct
.
(i.e. . dot operator)
Indirect member access operator Used to access a member of a struct which is referenced by
->
(i.e. -> arrow operator) the pointer
It is used to join multiple expressions together and to separate
the elements like variables and constants
, Comma operator E.g.
int i , j;
i=(j=10,j+20);
The sizeof operator returns the size of its operand in bytes.
Size() Size of operator Example : size of (char) will give us 1.
sizeof(a), where a is integer, will return 2.
& Address-of operator It specifies the address of the variable
printf() getch()
getche()
scanf() getchar()
gets()
putch()
putchar()
puts()
Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
C has 3 types I/O functions.
Character I/O
String I/O
File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar();
eg:
char c;
c=getchar();
Example Program
#include <stdio.h>
main()
{
int i;
char ch;
ch = getchar();
putchar(ch);
}
Output:
A
A
Example Program
void main()
{
char ch[30];
clrscr();
printf(“Enter the String : “);
gets(ch);
puts(“\n Entered String : %s”,ch);
puts(ch);
}
Output:
Enter the String : WELCOME
Entered String : WELCOME
Width Modifier: It specifies the total number of characters used to display the value.
Precision: It specifies the number of characters used after the decimal point.
E.g:
printf(“ Number=%7.2f\n”,5.4321);
Width=7
Precession=2
Output: Number = 5.43(3 spaces added in front of 5)
E.g:
printf(“Number=%07.2f\n”,5.4321)
Output:
Number=0005.4
3. Control Codes
They are also known as Escape Sequences.
21 Prepared by, A.LAURO EUGIN BRITTO AP/CSE ,
RVSETGI
E.g:
Control Code Meaning
\n New line
\t Horizontal Tab
\b Back space
Input Function scanf( )
It is used to get data in a specified format. It can accept data of different data types.
Syntax
scanf(“Control String”, var1address, var2address, …);
1.Branching
Jump-unconditional Branching
22 Prepared by, A.LAURO EUGIN BRITTO AP/CSE ,
RVSETGI
2.Iteration statements
Branching statements
Branching statements are used to transfer program control from one point to another.
There are 2 types of branching statements.
Conditional Branching:- Program control is transferred from one point to another based on the
result of some condition
Eg) if, if-else, switch
Unconditional Branching:- program control is transferred from one point to another without
checking any condition
Eg) goto, break, continue, return
Statement
Example:
#include <stdio.h>
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
if(n>0)
printf(“the number is positive”);
getch();
}
Output:
enter the number:50
23 Prepared by, A.LAURO EUGIN BRITTO AP/CSE ,
RVSETGI
the number is positive
T F
v) Switch statement
It is a multi way branch statement.
It provides an easy & organized way to select among multiple operations depending upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets executed.
4. If no match occurs, then all the statements after the default statement get executed.
Switch ,case, break and default are keywords
Break statement is used to exit from the current case structure
Flowchart
switch(expression)
case: break
statement
constant 0
case : break
constant 1 statement
default
statement break
Syntax
switch(expression)
{
case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;
…
case value n:
program statement;
program statement;
……
break;
default:
program statement;
program statement;
}
Example1
#include <stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
printf(“you entered an A\n”);
break;
case ‘B’:
printf(“you entered a B\n”);
break;
default:
printf(“Illegal entry”);
break;
}
getch();
}
Output
Enter a character
A
You entered an A
Output:
Enter a number
5
ODD
b)break statement
A break statement can appear only inside a body of , a switch or a loop
A break statement terminates the execution of the nearest enclosing loop or switch.
Syntax
break;
Example:1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2
Example :2
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
Syntax:
continue;
Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5
Example :2
#include<stdio.h>
main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}
return;
(or)
return expression;
for loop
It is the most popular looping statement. It is a pre test loop
Syntax:
for(initialization;condition2;incrementing/updating)
{
Statements;
}
2. while statement
They are also known as Entry controlled loops because here the condition is checked before the execution
of loop body.
Syntax:
while (expression)
{
statements;
}
3. do while statement
They are also known as Exit controlled loops because here the condition is checked after the execution of
loop body.
Syntax:
do
{
statements;
}
while(expression);
Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are nested.
Programs:
Sample output:
Enter a number: 5
5 is a prime number
PRE-PROCESSOR DIRECTIVES
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros.
Preprocessor directives are executed before compilation.
All preprocessor directives starts with hash # symbol.
1 #include Used to paste code of given file into current #include <filename>
file. It is used include system-defined and #include “filename”
user-defined header files. If included file is
not found, compiler renders error.
2 #define Used to define constant or micro #define PI 3.14
substitution. It can use any basic data type.
3 #undef Used to undefine the constant or macro #define PI 3.14
defined by #define. #undef PI
4 #ifdef Checks if macro is defined by #define. If #ifdef MACRO
yes, it executes the code otherwise #else //code
code is executed, if present. #endif
5 #ifndef Checks if macro is not defined by #define. #ifndef MACRO
If yes, it executes the code otherwise #else //code
code is executed, if present. #endif
6 #if Evaluates the expression or condition. If #if expression
condition is true, it executes the code //code
otherwise #elseif or #else or #endif code is #endif
executed.
7 #else Evaluates the expression or condition if #if expression
condition of #if is false. It can be used with //if code
#if, #elif, #ifdef and #ifndef directives. #else
//else code
#endif
8 #error Indicates error. The compiler gives fatal #error First include then
error if #error directive is found and skips compile
further compilation process.
9 #pragma Used to provide additional information to #pragma token
the compiler. The #pragma directive is used
by the compiler to offer machine or
operating-system feature
.
COMPILATION PROCESS
C is a high level language and it needs a compiler to convert it into an executable code so that the
program can be run on our machine.
How do we compile and run a C program?
Below are the steps we use on an Ubuntu machine with gcc compiler.
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
Then compile it using below command.
$ gcc – Wall filename.c – o filename
38 Prepared by, A.LAURO EUGIN BRITTO AP/CSE ,
RVSETGI
The option -Wall enables all compiler’s warning messages. This option is recommended to generate
better code.
The option -o is used to specify output file name. If we do not use this option, then an output file
with name a.out is generated.
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to become an
executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc – Wall – save-temps filename.c – o filename
Pre-processing
This is the first phase through which source code is passed. This phase include:
Removal of Comments
Expansion of Macros
Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i: using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our code is preserved.
Analysis:
printf contains now a + b rather than add(a, b) that’s because macros have expanded.
Comments are stripped off.
#include<stdio.h> is missing instead we see lots of code. So header files has been expanded and included
in our source file.
Compiling
The next step is to compile filename.i and produce an; intermediate compiled output file filename.s.
This file is in assembly level instructions. Let’s see through t his file using $vi filename.s
Assembly
In this phase the filename.s is taken as input and turned into filename.o by assembler.This file
contain machine level instructions. At this phase, only existing code is converted into machine language, the
function calls like printf() are not resolved. Let’s view this file using $vi filename.o
Linking
This is the final phase in which all the linking of function calls with their definitions are done. Linker
knows where all these functions are implemented. Linker does some extra work also, it adds some extra
code to our program which is required when the program starts and ends.
For example, there is a code which is required for setting up the environment like passing command line
arguments. This task can be easily verified by using $size filename.o and $size filename. Through these