Anda di halaman 1dari 63

Basics of C Programming

Header file
sample.c sample.i
#include<stdio.h> Preprocessor ------------------
----------------- (Includes header files int a, b;
----------------- in source file) -----------------
-----------------

complier
(changes program to machine language)

Library file
sample.exe
0001000011
00000011 1100001000 sample.obj
------------ Linker 000010000
1111111100 ---------------
0
Getting started
The C character set
Constants
• A constant is a quantity that does not change.
Integer, real and character constants
• 44, +765, -5000 are examples of integer constants
• 44.0, -34.65, +55.88765, 4.1e8, -0.2e+4 are examples of real
constants
• A character constant is a single alphabet, a single digit or a single
special symbol enclosed within single inverted commas.
• Both the inverted commas should point to the left. For example, ’A’ is
a valid character constant whereas ‘A’ is not.
• The maximum length of a character constant can be 1 character.
’ ’ - (space) is also a character constant

’-5 ’ --?? ’1.2 ’ --??


C variables
• An entity that may vary during program execution is called a variable.
• The rules for constructing different types of constants are different.
However, for constructing variable names of all types the same set of
rules apply. These rules are given below.

• A variable name is any combination of 1 to 31 alphabets, digits or


underscores.
• The first character in the variable name must be an alphabet or underscore.
• No commas or blanks are allowed within a variable name.
• No special symbol other than an underscore (as in gross_sal) can be used in a
variable name.
• These rules remain same for all the types of primary and secondary
variables.
• Naturally, the question follows... how is C able to differentiate
between these variables?
• C compiler is able to distinguish between the variable names by
making it compulsory for you to declare the type of any variable
name that you wish to use in a program.

Examples:
Keywords
• Keywords are the words whose meaning has already been explained
to the C compiler (or in a broad sense to the computer).
• The keywords cannot be used as variable names
• There are only 32 keywords available in C.
C Instructions
• There are basically three types of instructions in C:
• Type Declaration Instruction
• Arithmetic Instruction
• Control Instruction
Type Declaration Instruction
• Any variable used in the program must be declared before using it in
any statement.
• Data types which are also keywords are called primitive data types.
• The type declaration statement is written at the beginning of main( )
function

float b = a + 3.1, a = 1.5 ; //incorrect

long int: large integer values


double: large float values
Arithmetic Instruction
• A C arithmetic instruction consists of a variable name on the left hand
side of = and variable names & constants on the right hand side of =.
• The variables and constants appearing on the right hand side of = are
connected by arithmetic operators like +, -, *, and /.
Arithmetic Instructions
• C allows only one variable on left-hand side of =. That is, z = k * l is
legal, whereas k * l = z is illegal.
• Modular division operator (%) returns the remainder on dividing one
integer with another.
• The modulus operator (%) cannot be applied on a float.
• Also note that on using % the sign of the remainder is always same as
the sign of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2
yields 1
• No operator is assumed to be present. It must be written explicitly.
In the following example, the multiplication operator after b must be
explicitly written.
Integer and Float Conversions

k- integer variable
a-real variable
Hierarchy of Operations
• Within parentheses the same hierarchy as
mentioned in Figure is operative.
• In case of tie between operations of same priority
preference is given to the operator which occurs
first.
• EX.- i = 2*3/4 = 6/4 = 1 // L to R

• We must always remember to use pairs of parentheses. A careless imbalance of the right and left parentheses is a
common error. Best way to avoid this error is to type ( ) and then type an expression inside it.
Input/output Instruction
• printf()
• printf() is not keyword
• printf() is a predefined function
-prints text as it is (on console)
-prints value of expression or value of a variable

main()
{
printf(“This is ESW Lab”);
}
printf()
• The general form of printf( ) function is,
printf ( "<format string>", <list of variables> ) ;
<format string> can contain
-Characters that are simply printed as they are
-Conversion specifications that begin with a % sign
-Escape sequences that begin with a \ sign
• Escape sequences:
Input Instruction
scanf()
scanf(“format specifier”, variable address);
• scanf() is a predefined function
- Allows us to take value from keyboard
-Echoes (prints) the entered value on console

main()
{ &a - address of a
int a;
printf(“enter any value”)
scanf(“%d”, &a); Caution:
printf(“Entered value is =%d”, a); comma required between variable address
} no commas between format specifier
Some common rules while writing a C program
• Each instruction in a C program is written as a separate statement. Therefore a
complete C program would comprise of a series of statements.
• The statements in a program must appear in the same order in which we wish
them to be executed; unless of course the logic of the problem demands a
deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
• Blank spaces may be inserted between two words to improve the readability of
the statement. However, no blank spaces are allowed within a variable, constant
or keyword.
• All statements are entered in small case letters.
• C has no specific rules for the position at which a statement is to be written.
That’s why it is often called a free-form language.
• Every C statement must end with a ;. Thus ; acts as a statement terminator.
Some common rules while writing a C program
• Comment about the program should be enclosed within /* */.
• Sometimes it is not so obvious as to what a particular statement in a
program accomplishes. At such times it is worthwhile mentioning the
purpose of the statement (or a set of statements) using a comment.
• main( ) is a collective name given to a set of statements. This name
has to be main( ), it cannot be anything else. All statements that
belong to main( ) are enclosed within a pair of braces { }.
• Technically speaking main( ) is a function. Every function has a pair of
parentheses ( ) associated with it.
The Decision Control in C
• Many a times, we want a set of instructions to be executed in one
situation, and an entirely different set of instructions to be executed
in another situation. This kind of situation is dealt in C programs using
a decision control instruction.
• A decision control instruction can be implemented in C using:
(a) The if statement
(b) The if-else statement
(c) The switch-case statement
(c) The conditional operators
The if statement
General form: • In C a non-zero value is
if ( this condition/expression is true ) considered to be true
• To execute multiple statements
execute this statement ; write them within braces {}

Relational Operators:
The if-else statement
• The if statement by itself will execute a single statement, or a group of statements, when the
expression following if evaluates to true. It does nothing when the expression evaluates to false.

if ( this condition is true )


{
execute this statement ;
if block
and this;
}
else
{
execute this; else block
} Caution:
• No semi-colon after if(condition)
• Use braces for multiple statements
Study about use of Logical and Conditional Operators in decision control statements
The Loop Control Structure
• Also called iterative control instructions.
• Some situations involve repeating some portion of the program either
a specified number of times or until a particular condition is being
satisfied.
• This repetitive operation is done through a loop control structure.
(a) Using a for statement
(b) Using a while statement
(c) Using a do-while statement
The while loop
while(this condition/expression is true)
{
execute this;
}
// after this step control again goes to check the condition

The statements within the while loop would keep on getting executed till the condition being tested remains true.
When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
A sample program using while loop
main()
{
int i=1;
while (i<=4);
{
printf(“Loop successfully ran”);
i++;
}
}
The for loop
• Most popular.
• The for allows us to specify initialization, test and increment/decrement of the
loop in a single line
General structure:
for(initialize counter ; test counter ; increment counter )
{
do this;
and this;
}
Sample program using for loop
main()
{
int i;
for (i=1; i<=4; i= i+1)
{
printf(“Loop successfully ran”);
}
}

Learn about do while loop


Case Control Structure
• Choice between a number a alternatives rather than one or two.
• The control statement that allows us to make a decision from the number of
choices is called a switch, or more correctly a switch-case-default.
• Caution: When a match is found, the program executes the statements following that case, and all subsequent
case and default statements as well.
• If you want that only case 2 should get executed, you can achieve so by using a break keyword.
Some important points in switch
• You can in fact put the cases in any order you please.

multiple statements do not require braces as in if-else statements


• You are also allowed to use char values in case and switch as shown in
the following program:

In fact here when we use ‘v’, ‘a’, ‘x’ they are actually
replaced by the ASCII values (118, 97, 120) of these
character constants
• Every statement in a switch must belong to some case or the other. If a
statement doesn’t belong to any case the compiler won’t report an error.
However, the statement would never get executed. For example, in the following
program the printf( ) never goes to work.
Limitations of switch statement
• A float expression cannot be tested using a switch
• Cases can never have variable expressions (for example it is wrong to say
case a +3 : )
• Multiple cases cannot use same expressions. Thus the following switch is
illegal:

• one cannot have a case in a switch which looks like:


case i <= 20 :
Functions
• Piece of code to accomplish certain operation.
• Every C program can be thought of as a collection of these functions.
• Two types:
* Predefined functions Ex. printf( ), scanf( ) etc.
*User defined functions
An Example
Things to remember in functions
• C program is a collection of one or more functions.
• A function gets called when the function name is followed by a
semicolon.
• A function is defined when function name is followed by a pair of
braces in which one or more statements may be present.
• A function can be called any number of times.
• The order in which the functions are defined in a program and the
order in which they get called need not necessarily be same.
• A function can call itself. Such a process is called ‘recursion’.
• A function can be called from other function, but a function cannot be
defined in another function.
• Thus, the following program code would be wrong, since myfunction( ) is
being defined inside another function, main( ).

main( )
{
printf ( "\nI am in main" ) ;
myfunction( )
{
printf ( "\nI am in myfunction" ) ;
}
}
Why Use functions?
• Writing functions avoids rewriting the same code over and over.
• Using functions it becomes easier to write programs and keep track
of what they are doing.
• If the operation of a program can be divided into separate activities,
and each activity placed in a different function, then each could be
written and checked more or less independently.
• Separating the code into modular functions also makes the program
easier to design and understand.
Passing Values between Functions
• In this program, from the function main( ) the values of a, b and c are passed on
to the function calsum( ), by making a call to the function calsum( ) and
mentioning a, b and c in the parentheses:

sum = calsum ( a, b, c ) ;

In the calsum( ) function these values get collected in three variables x, y and z:

calsum ( x, y, z )
int x, y, z ;

• The variables a, b and c are called ‘actual arguments’, whereas the variables x, y
and z are called ‘formal arguments’. Any number of arguments can be passed to
a function being called. However, the type, order and number of the actual and
formal arguments must always be same.

• Instead of using different variable names x, y and z, we could have used the
same variable names a, b and c. But the compiler would still treat them as
different variables since they are in different functions.
• There are two methods of declaring the formal arguments. The one that we have
used in our program is known as Kernighan and Ritchie (or just K & R) method.

calsum ( x, y, z )
int x, y, z ;

Another method is,


calsum ( int x, int y, int z )
Function declaration and prototypes
• Any C function by default returns an int value. If we desire that a function should return a value
other than an int, then it is necessary to explicitly mention so in the calling function as well as in
the called function
• Note that the function square( ) must be declared in main( ) as
float square ( float ) ;

• This statement is often called the prototype declaration of the


square( ) function. What it means is square( ) is a function that
receives a float and returns a float.

• We have done the prototype declaration in main( ) because


we have called it from main( ).

• There is a possibility that we may call square( ) from several


other functions other than main( ). Does this mean that we
would need prototype declaration of square( ) in all these
functions..? No, in such a case we would make only one
declaration outside all the functions at the beginning of the
program.
• In some programming situations we want that a called
function should not return any value. This is made possible by
using the keyword void.
Ways to define a function based on input
argument type and return type
• Takes Nothing, Returns Nothing
• Takes Something, Returns Nothing
• Takes Nothing, Returns Something
• Takes Something, Returns Something
Takes Nothing Returns Nothing
#include <conio.h>
#include<stdio.h>
main()
{
void add(void); //Function declaration
add(); // function is called here
}
void add () // function definition
{
int a, b, c;
printf(“Enter the nembers”);
scanf(“%d%d”, &a&b);
c=a+b;
printf(“sum is %d”, c);
}
Takes Something Returns Nothing
#include <conio.h>
#include<stdio.h>
• In function definition a and b could be replaced
by x and y.
main()
• Function can also be declared globally (before
{
main()), if it is called by more than once
int x, y;
function.
void add(int, int); //Function declaration
• The number of arguments in the function
clrscr();
definition depend upon the number of value it
printf(“Enter two numbers”);
needs to do its job.
scanf(“%d%d”,&x,&y); • Values of x and y will be passed to a and b in
add(x,y); // function is called here this program
}
void add (int a, int b) // function definition
{
int c;
c=a+b;
printf(“sum is %d”, c);
}
Takes Nothing Returns Something
#include <conio.h>
#include<stdio.h> • return can be used to pass only one value
main() • return<space>c is also correct
{ • return a+b will return wrong value
int s; • return(a+b) is correct
int add(void); //Function declaration • return immediately passes the control to main
clrscr(); function
s=add(); // function is called here
printf(“sum is %d”, s);

int add () // function definition


{
int a, b, c;
printf(“Enter two numbers”);
scanf(“%d%d”, &a, &b);
c=a+b;
return(c);
}
Takes Something Returns Something
#include <conio.h>
#include<stdio.h>
main()
{
int s, x, y;
int add(int, int); //Function declaration
printf(“Enter two numbers”);
scanf(“%d%d”, &x&y)
s=add(x,y); // function is called here
printf(“sum is %d”, s);

int add (int a, int b) // function definition


{
int c;
c=a+b;
return(c);
}
Recursion
• In C, it is possible for the functions to call themselves.
• A function is called ‘recursive’ if a statement within the body of a
function calls itself.
3 2 1

2 1
Arrays
• There are situations in which we would want to store more than one
value at a time in a single variable.
• An array is collective name given to similar quantities.
• Array is also known as Subscript variable.
• Array is collection of similar quantities. These similar elements could
be all ints, or all floats, or all chars etc.
• marks- name of the array
• 30- dimension or total number of
elements in array
• Elements are indexed starting from 0
• marks[1] is second element of the array
• Last element of the array is marks[29]
Declaration of Arrays
• int a[]; incorrect
• int a[7];
• Till arrays are not given any specific values, they are supposed to
contain garbage values.
• Initialization:
• int a[4]={2, 6, 8, 5}
-Here a[0] is 2, a[1] is 6 .
• int a[]={2, 6, 8, 5} is also correct
• int a[4]={2, 6, 8, 5, 6, 99, 2}; error
• int a[4]={2,6}; rest of the values will be zero(not garbage value)
Two dimensional arrays
a
• int a[6]; 0 1 2 3 4 5

b
• int b[2][3]; 0 1
0 1 2 0 1 2

b
0 1 2
0

1 0 1 2
Sample Program

Initialization:

int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;


Preprocessor
• Preprocessor is a program that processes our
source program before it is passed to the
compiler.
• Each of these preprocessor directives begin
with a # symbol.
Preprocessor directives/commands
• Macro expansion
This statement is called ‘macro definition’ or more commonly,
just a ‘macro’

PI- macro template


3.1415- macro expansion

When we compile the program, before the source code passes to the compiler it is examined by the C
preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program
in search of the macro templates; wherever it finds one, it replaces the macro template with the appropriate
macro expansion. Only after this procedure has been completed is the program handed over to the compiler.
Preprocessor commands
File inclusion: Header files
• A header file is a file with extension .h which contains declarations and
macro definitions. (to be shared between several source files)
• Types
1. The one which comes with you compiler: #include <stdio.h> etc.
tells the C preprocessor to get stdio.h from your system libraries and add
the text to the current source file.

2. The files which programmer writes for specific purpose.


Ex- #include ”myheader.h”
tells CPP to get myheader.h from the local directory and add the content to
the current source file.
Working with header files
Header file Main or Source file (saved in same location)

void add(int m1,int n1,int m2, int n2,int mat1[m1][n1],int #include <stdio.h>
mat2[m2][n2],int mat3[m1][n1]) #include "matrixheader.h"
{
/* Definition of function is done here*/ void main()
---------------------------------- {
---------------------------------- -------------------
} add(m1,n1,m2,n2,mat1,mat2,mat3); //function is called here
}
Save it as matrixheader.h
Not covered
• Pointers
• FILE handling in C
References
• Let us C by Yashwant Kanetkar (most of the text and images have
been taken form this book)
• Programming in ANSI C by E. Balagurusamy
• C Tutorial (in Hindi) by MySirG.com youtube channel
• https://www.geeksforgeeks.org/
Thank You

Anda mungkin juga menyukai