Fundamentals of C Programming Module 1
3045 :Fundamentals of C Programming
MODULE 1
• Introduction to Programming concepts: Structure of a C
program - Keyword, Variables, Constants,Data types
and type qualifiers. Output and input functions,
Operators - Arithmetic, relational, logical,
increment/decrement, conditional, assignment, bit
wise, Assignment, Conditional and type casting.
Page 1
Fundamentals of C Programming Module 1
Importance of C
C is a robust language whose rich set of built-in functions and
operations can be used to write any complex program.
Programs written in C are efficient and fast.(due to variety of data types
and powerful operators)
C is highly portable.
portable→ C programs written on one computer can be run
on another computer with little or no alteration.
C programming is well suited for structured programming.
Sample Program to Display "Hello, World!"
#include <stdio.h>
int main() {
/*.... printf() displays the string inside quotation....*/
printf("Hello, World!");
return 0;
}
Output
Hello, World!
Every program must have exactly one main function.
Empty pair of parentheses (main())immediately following main function
indicates the function main has no arguments.
Opening brace “{“ marks the beginning of the program.
Closing brace “}” in the last line indicates the end of the function.
All the statements between these two braces form the function body.
printf is a predefined standard C function for printing output.
#include <stdio.h> is the header file.
Page 2
Fundamentals of C Programming Module 1
Basic Structure of C Programs
C program can be viewed as a group of building blocks called functions. A
function is a subroutine that may include one or more statements designed to
perform a specific task.
Section Description
Documentation Consists of the description of the program, programmer's
name, and creation date. These are generally written in the
form of comments.
Link All header files are included in this section which contains
different functions from the libraries. A copy of these header
files is inserted into your code before compilation.
Definition Includes preprocessor directive, which contains symbolic
constants. E.g.: #define allows us to use constants in our
code. It replaces all the constants with its value in the code.
Global Includes declaration of global variables, function
Declaration declarations, static global variables, and functions.
Main() For every C program, the execution starts from
Function the main() function. It is mandatory to include
a main() function in every C program.
This section contains two parts declaration part and
executable part.
Declaratation part declares all the variables used in
executable part.
Page 3
Fundamentals of C Programming Module 1
There is atleast one statement in executable part .
The program begins at the opening brace and ends at the
closing brace.
Subprograms Includes all user-defined functions (functions the user
provides). They can contain the inbuilt functions and the
function definitions declared in the Global Declaration
section. These are called in the main() function.
Comments
Comments can be written in the program to describe the details about each
line of code etc.
Types of comments
There are two types of comments in C language.
1. single line comment 2. multi line comment
Single line comment
Single line comment if that statement starts with //
Example: //This is for finding the sum of two numbers
Multiline comments
Multi line comment begins with /* and it ends with*/.
Eg: /* This is for finding average of numbers*/
Header files
Syntax to include header file is
#include <filename>
Example
#include<stdio.h> is a header file containing declarations for
input/output routines(functions).
printf(),scanf()
Page 4
Fundamentals of C Programming Module 1
#include< math.h> contains declarations for certain mathematical
functions
pow(),sqrt()
Tokens in C
The smallest individual units in a C program are known as a C tokens.C has six
types of tokens as shown below:-
1. Keyword - reserved words E.g. if, float, for etc.
2. Identifier - name of variable, function etc.
3. Operators - +, -, *, /, % && etc.
4. Constant - fixed values, cannot be changed
5. Strings -group of characters.- “Hello” “ok”
6. Special symbols- {, ( )}[ ] # & -> etc.
C character set
We can use the following character set for writing the C program.
They are called C character sets.
● uppercase letters AtoZ
● lowercase letters atoz
● Digits 0to9
● certainspecial characters . , ; !#$%^&*()_+|\”;:~{}[]< >
● White spaces: Blank space, horizontal space, carriage return,
new line, form feed
Identifiers and keywords
Keywords
Keywords are reserved words.
Page 5
Fundamentals of C Programming Module 1
They have standard, predefined meanings and purposes in C language.
They cannot be used as identifiers
The standard keywords are:-
Keywords are written in lowercase letters
Identifiers
Identifiers are names that are given to various program elements, such as
● Variables
● functions
● Arrays
● Structures
Rules for writing identifier (variable, function name, array name etc)
1. Identifiers can consist of the following only:
○ Letters ■ Uppercase a to z and lowercase A to Z
○ Underscore_ ■ Underscore _ is also treated as a letter.
○ Digits ■ 0 to 9
Page 6
Fundamentals of C Programming Module 1
2. First character must be a letter or underscore
3. Case sensitive. Upper- and lowercase letters are not
interchangeable
4. Keywords cannot be used as identifiers
5. Must not contain space.
6. Only first 31 characters are significant
E.g for valid identifiers
X Y12 sum_1 _ temperature a1bc3_
names area tax_rate TABLE table Branch12_4_z
base_num12
CONSTANTS
Constants in C refers to the fixed values that do not change during
execution of program.
E.g. 23, “hello” , 3.45
There are four basic types of constants in C.
Integer and Real constants represent numbers.
Page 7
Fundamentals of C Programming Module 1
They are often referred to as numeric-type constants.
Integer Constants
An integer constant refers to a sequence of digits.
Integer constants are of three types:
● decimal (base lO)
● octal (base 8)
● hexadecimal (base 16)
Real Constants(Floating point Constants)
A real constant is combination of a whole number followed by
a decimal point and the fractional part.
Example: 0.0083 -0.75 .95
215.
Character Constants
A character constant is a single character, enclosed in single
quotation marks. Some character constants are shown below.
' A ' ' X’ '3' ‘?’ ‘’
Backslash Character Constants
Escape sequences are also known as Backslash Character
Constants.
A backslash ( \ ) followed by one or more special character
is known as escape sequence. The escape sequence is used
to express some action.
\n stands for new line character
Page 8
Fundamentals of C Programming Module 1
String Constants
A String constant is a sequence of characters enclosed in
double quotes.
Some string constants are shown below.
"green" "Washington, D.C. 20005” "270-32-3456"
"$19.95" "THE CORRECT ANSWER IS:”
DATA TYPES
C supports several different types of data.
Each type of data specifies how that data is represented within the
computer’s memory
Different types of data types:
1. Primary/Fundamental/basic data type : int, char,float, double ,void
2. Derived data types : array, pointer,functions,constants
3. User defined data types : structure, union, enumeration
Primary Data Types
C’ compilers support four fundamental data types. They are as follows –
Data type Keyword Memory size
• Integer int 2 or 4 byte
• Character char 1 byte
• Floating – point float 4 byte
Page 9
Fundamentals of C Programming Module 1
• Double precision floating double 8 byte
point
Integral data type
Integral data types are used to store whole numbers and characters.
It is further classified into two types −
• Integer data type.
• Character data type.
Integer data type (int)
• int : for integers (2 byte memory space allocates in memory)
• The integer storage are short int , int and long int in both signed and
unsigned forms.
Character data type(char)
• A single character can be defined as a character(char) type data.
• char : for characters(1 byte memory space allocates in memory)
Page 10
Fundamentals of C Programming Module 1
Floating point data type
• 3 types: float, double, long double
• float : for floating point numbers(4 byte memory space allocates
in memory) with 6 digits of precision.
• double: for double precision floating point numbers(8 byte
memory space allocates in memory) with 14 digits precision
• long double: 80 bits
Void
• The void has no values
• Usually used to specify the type of functions. The type of a function is
said to be void when it does not return any values to the calling
function.
Derived data types
Derived data types are constructed from fundamental data types.
They are
1. Arrays: An array is a collection of variables of the same type that are
referenced by a common name.
2. Functions: A function is a named part of a program that can be
invoked from other part of the program.
3. Pointer: A pointer is a variable that holds the memory address. This
address is usually the location of another variable in memory.
4. Constant: The keyword const can be added to the declaration of an
object to make that object a constant rather than a variable. Thus, the
variable of the named constant cannot be altered during the program
run.
Syntax
const type name = value;
Eg: const int a=10;
User defined data types
Structure: A structure is a collection of variables of different data types
referenced under one name.
Enumeration: Enumerated data type (also called enumeration or enum)
provides a way for attaching names to numbers there by increasing
comprehensibility of the code.
It has the following form.
Page 11
Fundamentals of C Programming Module 1
enum identifier {value1,value2,…….,value n};
The identifier is a user defined enumerated data type which can be
used to declare variables that can have one of the values enclosed
with in the braces (known as enumeration constant).
Eg: enum week_day {Monday, Tuesday...Sunday};
// an enumerated data type week_day has been defined
Union:
Structure and union are same but different in memory allocation.
A union can be declared using the keyword is union.
A union is a memory location that is shared by two or more different
variables, generally of different types at different times.
Defining a union is similar to defining a structure.
Variables
• A variable is a data name that may be used to store a data value.
• A variable name can be chosen by the programmer
• A variable name may consist of letters,digits and the underscore(_)
• Conditions
1. They must begin with a letter
2. ANSI standard recognize a length of 31 characters
3. Uppercase and lowercase characters are significant
4. It should not be a keyword
5. White space is not allowed
Examples
John value mark T_raise
sum1 x1
Declaration of Variables
Declaration does two things
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
Page 12
Fundamentals of C Programming Module 1
Primary type declaration
Syntax
data-type v1,v2,v3,......,vn;
v1,v2,v3,......,vn are the name of variables
Declaration statement must end with a semicolon ;
Variables are separated by commas
Example
int count;
int number, total;
double ratio;
Assigning values to variables
Assignment statement(using assignment operator)
Variable_name = constant;
Example
a=5;
start= 1;
d=b+10;
a=a+1;
During assignment operation, C converts type of variable on the right
hand side to type of value on the left.
Can also assign value to a variable at the time of declaration
datatype variable_name = constant;
Example
int start =0;
int a, b=10;
Page 13
Fundamentals of C Programming Module 1
The process of assigning initial value to a variable is called
initialization.
Reading data from Keyboard
Another way of giving values to variables is to input data through keyboard
using the scanf function
scanf(“control string”,&variable1,&variable2,....);
Control string contains format of data being received.
The ampersand symbol ‘&’ before variable name is an operator
that specifies the variable names address.
Example
scanf(“%d”, &number);
%d specifies that an integer value is read from the terminal
Declaring a variable as CONSTANT
We want certain variables to remain constant during the execution of a
program, this can be achieved by declaring the variable with the qualifier
const at the time of initialization.
const int class_size = 40;
Declaring a variable as VOLATILE
Qualifier volatile is used to tell explicitly the compiler that a variable’s
value may be changed at any time by some external sources(from
outside the program).
For example
volatile int date;
Operators
An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations.
Page 14
Fundamentals of C Programming Module 1
C operators can be classified into a number of categories.They include:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Arithmetic Operators
The modulo division operation produces the remainder of an integer
division.
Modulo division operator (%) cannot be used on floating point data.
Eg: a-b a+b
a*b a/b
a%b -a*b
Here a and b are variables and are known as operands
Relational Operators
A relational operator checks the relationship between two operands.
If the relation is true, it returns 1; if the relation is false, it returns value
0.
Page 15
Fundamentals of C Programming Module 1
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
Logical Operators
An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false.
Operator Meaning Example
Logical AND. True only If c = 5 and d = 2 then,
&& if all operands are expression ((c==5)
true &&(d>5)) equals to 0.
Logical OR. True only If c = 5 and d = 2 then,
|| if either one operand expression ((c==5) ||
is true (d>5)) equals to 1.
Logical NOT. True only If c = 5 then, expression
!
if the operand is 0 !(c==5) equals to 0.
Page 16
Fundamentals of C Programming Module 1
Assignment Operators
An assignment operator is used for assigning a value to a variable.
The most common assignment operator is ‘=’
C has a set of shorthand assignment operators of the form
v op = exp;
where v is a variable, exp is an expression and op is a C binary arithmetic
operator.
Operator Example Same as
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to
change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases
the value by 1.
These two operators are unary operators, meaning they only operate on
a single operand.
++m or m++;
--m or m--
++m is equivalent to m =m+1; (or m +=1;)
Page 17
Fundamentals of C Programming Module 1
--m is equivalent to m =m-1;( or m -= 1;)
A prefix operator first adds 1 to the operand and then the result is assigned to
the variable on left. On the other hand, a postfix operator first assigns the
value to the variable on left and then increment the operand.
Example
m=5;
y= ++m; (prefix)
In this case the value of y and m would be 6
m=5;
y =m++; (postfix)
In this case the value of y is 5 and m is 6
Conditional Operator(Ternary Operator)
exp1 ? exp2 : exp3
The operator ? works as follows :
exp1 is evaluated first if it is true then the exp2 is evaluated and
becomes the value of expression.
If exp1 is false,exp3 is evaluated and its value becomes the value
of expression
Consider the example
int a=10;
int b=15;
int x;
x= (a>b)? a: b;
In this example x will be assigned the value of b. This can be achieved
using the if….else statement as follows
if (a>b)
x=a;
Page 18
Fundamentals of C Programming Module 1
else
x=b;
Bitwise Operators
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
Shift left
>> Shift right
VARIOUS INPUT/OUTPUT FUNCTIONS
getchar ( )
getchar () function reads a single character from standard input.
It takes no parameters and its returned value is the input
character.
It has the following form
variable name=getchar( );
Eg: char c;
printf(“Enter a character”);
c=getchar ( );
The second line causes a single character to be entered from the
standard input device and then assigned to c. The variable name has
been declared as ‘char’ type.
putchar( )
It displays a single character on the screen.
This function takes one argument, which is the character to be sent.
It also returns this character as its result.
The general form is
putchar ( variable-name);
Page 19
Fundamentals of C Programming Module 1
Eg: char ans=’y’
putchar (ans);
gets( ) : receives a string from the keyboard.
puts ( ) : Outputs a string to the screen
Eg: char vehicle [40];
printf(“Enter your vehicle name”);
gets (vehicle);
puts (vehicle);
These lines use the gets and puts to transfer the line of text into
and out of the computer.
When this program is executed, it will give the same result as that
with scanf and printf function for input and output of givenvariable or array.
clrscr ( ) : It is a clear screen function.
printf ( ) : For outputting the result we use printf( ) function.
Syntax
printf (“formatted string”, variable);
Eg: printf (“%d”, a);
printf (“WELCOME MY FRIEND”);
Formatted strings are
1. %d integers
2. %f float
3. %c character
4. %o octal number
5. %s string
6. %e exponential notation
7. %u unsigned integer
8. %x hexadecimal integer
9. % i signed decimal integer
10. %p display a pointer
11. %% prints a percent sign (%)
Page 20
Fundamentals of C Programming Module 1
scanf ( )
It can read data from keyboard.
scanf ( ) means “scan formatted” .
Syntax
scanf (“formatted string”, addressed variable);
Eg: scanf (“%d”, &a);
scanf (“%d%f”,&num1,&num2);
Page 21