0% found this document useful (0 votes)
2 views24 pages

Module 1 C Programming

The document provides an introduction to the C programming language, detailing its history, character set, and fundamental concepts such as algorithms and flowcharts. It explains the structure of a C program, including documentation, preprocessor directives, and the main function, along with the definitions of tokens, variables, constants, and operators. Additionally, it includes examples of algorithms and flowcharts for problem-solving methodologies.

Uploaded by

ksmadhusudhan78
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Module 1 C Programming

The document provides an introduction to the C programming language, detailing its history, character set, and fundamental concepts such as algorithms and flowcharts. It explains the structure of a C program, including documentation, preprocessor directives, and the main function, along with the definitions of tokens, variables, constants, and operators. Additionally, it includes examples of algorithms and flowcharts for problem-solving methodologies.

Uploaded by

ksmadhusudhan78
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to C Programming DSCE

Module 1
Introduction to C
C has emerged as the most widely used programming language for software development. C is a
general-purpose high level language that was originally developed by Dennis Ritchie for the Unix
operating system. It was first implemented on the Digital Equipment Corporation PDP -11
computer in 1972. C language supports the powerful low level features like pointer, memory
allocation, bit manipulations etc. The features of C language make it possible to see the language
for system programming like the development of compiler, interpreter, operating system, system
utilities etc.

‘C’ language fundamentals:

As we know to learn any language we should first know alphabets, words, sentences, and
paragraph.

i) Character set or alphabets are:-

Any symbol that you ar0e using while writing programs is called as character or alphabet. using
this you can obtain meaningful expression, statements
Character set are the set of alphabets, letters and some special characters that are valid in C
language.

 Alphabe ts:
Uppercase: A B C .................................... X Y Z
Lowercase: a b c ...................................... x y z

 Digits: 0 1 2 3 4 5 6 7 8 9 10

 Spe cial Characters:

, < > . ( ) ; $ : % [ ] ‘ & { } “ ^ !* / | \

 White s pace Characters :


Blank space, new line (\n), horizontal tab (\t), carriage return (\r) and form feed

Dr. Shobha N, Assistant Prof., CSD 1


Introduction to C Programming DSCE

VI. Special Symbols

 Escape Sequences
Sometimes, it is necessary to use newline (enter), tab, quotation mark etc. in the program which
either cannot be typed or has special meaning in C programming. In such cases, escape sequence
are used. For example:
\n is used for newline.

\t is used to give tab space

\f form feed

\r return

\v vertical tab

\’ single quotation mark

\” double quotation mark


\0 null character
\ (backslash) causes "escape" from the normal way the characters are interpreted by the compiler.

Algorithm and Flow Chart

Problem Solving Methodologies


1. Algorithm
2. Flowchart

1. Algorithm
A step by step procedure usually written in ordinary Language to solve a given problem is called
Algorithm.
Example Algorithms:
1. Write an algorithm to calculate the simple interest using the formula. Simple interest = P*N*
R/100. Where P is principle Amount, N is the number of years and R is the rate of interest.
Step 1: Read the three input quantities P, N and R.
Step 2: Calculate simple interest as Simple interest = P* N* R/100
Step 3: Print simple interest.

Dr. Shobha N, Assistant Prof., CSD 2


Introduction to C Programming DSCE

Step 4: Stop.
2. Write an algorithm to find the area of the triangle.
Let b, c be the sides of the triangle ABC and A the included angle between the given sides.
Step 1: Input the given elements of the triangle namely sides b, c & angle between the sides
A.
Step 2: Area = (1/2) *b*C* sin A
Step 3: Output the Area
Step 4: Stop.
3. Write algorithm to find the factorial of a given number N
Step 1: PROD  1
Step 2: I0
Step 3: read N
Step 4: While I < N do
4.1 I  I + 1
4.2. PROD  PROD* I
Step 5: Write “Factorial of”, N, “is”, PROD
Step 6: end.
3. Add two numbers
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
4. Find largest among three numbers
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a > b

Dr. Shobha N, Assistant Prof., CSD 3


Introduction to C Programming DSCE

If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

5. Check whether the number is prime or not


Step 1: Start
Step 2: Declare variables n, i, flag.
Step 3: Initialize variables
flag ← 1
i←2
Step 4: Read n from the user.
Step 5: Repeat the steps until i=(n/2)
5.1 If remainder of n÷i equals 0
flag ← 0
Go to step 6
5.2 i ← i+1
Step 6: If flag = 0
Display n is not prime
else
Display n is prime
Step 7: Stop

Dr. Shobha N, Assistant Prof., CSD 4


Introduction to C Programming DSCE

Flowchart
A flow chart is a step by step diagrammatic representation of the logic paths to solve a given
problem or a flowchart is graphical representation of an algorithm.

The symbols that we make use while drawing flowcharts:


a) Oval: Rectangle with rounded sides is used to indicate either START/ STOP of the
program.

b) Input and output indicators: Parallelograms are used to represent input and output
operations. Statements like INPUT, READ and PRINT are represented in these
Parallelograms.

c) Process Indicators: Rectangle is used to indicate any set of processing operation such as
for storing arithmetic operations.

d) Decision Makers: The diamond is used for indicating the step of decision making and
therefore known as decision box. Decision boxes are used to test the conditions or ask
questions and depending upon the answers, the appropriate actions are taken by the
computer.

e) Repetitions or Looping Statements: The hexagon is used for indicating Repetition or loop
which is normally used to execute a group of instructions for a specified number of times.

Dr. Shobha N, Assistant Prof., CSD 5


Introduction to C Programming DSCE

f) Flow Lines: Flow lines indicate the direction being followed in the flowchart. In a
Flowchart, every line must have an arrow on it to indicate the direction. The arrows may
be in any direction.

g) On- Page connectors: Circles are used to join the different parts of a flowchart and these
circles are called on-page connectors

h) Off-page connectors: This connector represents a break in the path of flowchart which is
too large to fit on a single page.

Add two numbers entered by the user

Dr. Shobha N, Assistant Prof., CSD 6


Introduction to C Programming DSCE

Largest among three numbers

Draw a flowchart for adding the integers from 1 to 100 and to print the sum

Dr. Shobha N, Assistant Prof., CSD 7


Introduction to C Programming DSCE

Structure of C Program

Q. Explain the structure of ‘C’ Program


C program structure:

Documentation --General Comments


Preprocessor directives
Global variables;
main ( ) function
{
local variables;
statements;
--------------
--------------
}
function1( ) other functions
{
local variables;
statements;
--------------
-------------- }

/*Example number 1*/ -----------Documentation


#include<stdio.h> -----------Preprocessor directives
main ( ) -----------main ( ) function
{
Printf (“This is first program \n”); ----------- statements
}

Description:

a. Documentation:
Documentation is general description about program. It can be given as comments. Comment
statements doesn’t compile by the computer. Two different types of comments are
1) Single line comment: - it starts with //. Anything written after // will be ignored by compiler (till
the end of line)
2) Double line or multiline comment: - it starts with /* called opening comment mark ……..
............................and end with closing comment mark*/
The C compiler ignores everything between the opening comment mark and closing comment
mark.
The comment is used for program documentation.

Dr. Shobha N, Assistant Prof., CSD 8


Introduction to C Programming DSCE

b. Preprocessor directives
#include directory:
In C, #include is a preprocessor directive that tells the C preprocessor to look for a file and place the
file in the location where #include indicates. The preprocessor includes the header file such as stdio.h,
conio.h, string.h etc.

Header file:
The file that are included by the #include directive such as stdio.h is called header [Link] header
files are always placed at the start of a C [Link] files should be written in Angular < > braces.
Header files contain different predefined functions that are required to run the program.

c. main ( ) function
Every C program must have one and only one main functions. The main function can be put anywhere
but the execution of a program starts with main function. The main function starts with {curly braces
and end with} curly braces

Every program statements must end with a semi colon (;). All programming statements must lie
within curly braces.

1, What is Token? What are different types of tokens available in C language? Explain.

Keywords

Identifiers

Constants

C Tokens
Operators

Special
Symbol

 Keywords:

- Keywords are the reserved words used in programming.

Dr. Shobha N, Assistant Prof., CSD 9


Introduction to C Programming DSCE

- Each keyword has fixed meaning and that cannot be changed by user.
- The keywords are also called as reserved words. The meaning of the keywords already
given to the compiler. There are 32 keywords available in C.

For example:

auto double int struct break long else switch case


enum register typedef else char extern return
union const float short unsigned
continue for signed void default goto

ii) Identifiers
An identifiers can be defined as the name of the variable, function, arrays, structures, constants
etc, are created by the programmer. They are the fundamental requirements of any programming
language.

 Identifiers:

In C programming, identifiers are names given to C entities, such as variables, functions, structures
etc. Identifier is created to give unique name to C entities to identify it during the execution of
program.

Example: int i , is a identifier which denotes a variable of type integer.

Identifiers are used to store the data as well as instruction. Each piece of data or instruction is
stored at unique address in the memory.

Rules for writing ide ntifier

- An identifier can be composed of letters (both uppercase and lowercase letters), digits and
underscore '_' only.
- The first letter of identifier should be either a letter or an underscore.
- Maximum length of an identifier is 31 characters.
- Reserved words cannot be used as identifier.
-

Valid identifier Invalid identifier

Sum_of for
i if
_name sum-of

 Delimiters:

Dr. Shobha N, Assistant Prof., CSD 10


Introduction to C Programming DSCE

Delimiters are used for syntactic meaning in C. These are as given below-

; Semicolon end of statements


() parenthesis used in expression
{} curly braces used for block of statements
[] square bracket used for array
# hash preprocessor directives
, comma variables delimiter

iii) Variable:

A variable is a named data storage location in computers memory. By using a variable name we
are referring to the data stored in the location. A value that changes during the execution of the
program is called variable.
Each variable in C has a specific type, which determines the size and layout of the variable's
memory

Syntax for declaration of a variable:

data type variable name ;

Examples of variable name: sum, car_no, count etc.

Rules of variables declaration in C:


- The variable name is a combination of alphabets, digits, underscore etc.
- The first character in the variable name must be an alphabet.
- No comma or blanks are allowed in variable name.
- No special symbols ($, #) other than underscore can be used in variable name.
- Uppercase & lowercase letters are distinct i.e. case sensitive
- A variable name can’t start with digit.
- ANSI C it supports up to 31 characters long variable name.

iv) Constants:

A constant is a data item the value of which will not change during the execution of program.
‘C’ has 3 basic types of constant:

 Numeric constant
o Integer constant
o Floating point constant
 Character constant
 String constant

Dr. Shobha N, Assistant Prof., CSD 11


Introduction to C Programming DSCE

1. Numeric constant

 Integer constant
An integer constant has only numbers from 0 to 9. Examples are: 0, 4, 111, and 6598

 Floating point constant


A floating point constant is a numeric constant with a decimal point are an exponent or both.
Eg: 0.5 488.33 1.56 e +9 9e-5

2. Character constant

Character constants are the constant which use single quotation around characters.
For example: 'a', 'l', 'm', ‘F’, ‘A’ ‘C’ ‘X’.

3. String Constant

The group of characters which represents with double quotes is a string constant.
Eg: “PRIME” , “COLLEGE”

V. Operators:

Types of C operators: C language offers many types of operators. They are,


Types of C operators: C language offers many types of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

1. Arithmetic Operators :-

These are used to perform mathematical calculations like addition, subtraction, multiplication,
division and modulus,(+,-,,*, / ,% ) respectively.

‘C’ programming Example:-


/* Program to demonstrate the working of arithmetic operator in c */
#include<stdio.h>
void main( )

Dr. Shobha N, Assistant Prof., CSD 12


Introduction to C Programming DSCE

{
int a=9 ,b=4, add,sub,mul,div,mod ;
add=a+b;
printf(“a+b=%d\n”, add);
sub=a-b;
printf(“a-b=%d\n”, sub);
mul=a*b;
printf(“a*b=%d\n”, mul);
div=a/b;
printf(“a/b=%d\n”, div);
mod=a%b;
printf(“remainder=%d\n”, mod);
}
output:
a+b=13
a-b =5
a*b =36
a/b =2
remainder=1

2. Assignment operators :-

The most common assignment operator is =. This operator assigns the value in right side to
the left side. For example:

= Simple assignment operator, Assigns values of right side operands to left side operand

Ex. C = A + B will assign value of A + B into C

‘C’ programming Example:-

# include <stdio.h>
void main()
{
int Total=0,i;
for (i=0;i<10;i++)
{
Total+=i; // This is same as Total = Total+i
}
printf("Total = %d", Total);

Dr. Shobha N, Assistant Prof., CSD 13


Introduction to C Programming DSCE

Operators Example Explanation


Simple assignment
= sum=10 10 is assigned to variable sum
operator
This_is_same_as_sum=sum+10……
+= sum+=10
……
-= sum-=10 This is same as sum = sum-10
*= sum*=10 This is same as sum = sum*10
Compound assignment
operators /+ sum/=10 This is same as sum = sum/10
%= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10

3. Relational operators

Relational operators are used to find the relation between two variables. i.e. to compare the values
of two variables in a C program. The result will be true or false .true is always one and false is
zero.

[Link] Operators Example Description


1 > (greater than) x>y x is greater than y
2 < (less than) x<y x is less than y
3 >= (greater/equal) x >= y x is greater than or equal to y
4 <= (lesser /equal) x <= y x is less than or equal to y
5 == (equal) x == y x is equal to y
6 != (not equal) x != y x is not equal to y

‘C’ programming Example:-


1)

#include <stdio.h>
void main( )
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}

Dr. Shobha N, Assistant Prof., CSD 14


Introduction to C Programming DSCE

else
{
printf("m and n are not equal");
}
}
Output: m and n are not equal

 In this program, relational operator (==) is used to compare 2 values whether they are equal
are not.
 If both values are equal, output is displayed as” values are equal”. Else, output is displayed
as “values are not equal”.

2)
#include<stdio.h>
main()
{
int num1 = 30;
int num2 = 40;
printf("Value of %d > %d is %d",num1,num2,num1> num2);
printf("Value of %d >=%d is %d",num1,num2,num1>=num2);
printf("Value of %d <=%d is %d",num1,num2,num1<=num2);
printf("Value of %d < %d is %d",num1,num2,num1< num2);
return(0);
}
Output:-

Value of 30 > 40 is 0
Value of 30 >=40 is 0
Value of 30 <=40 is 1
Value of 30 < 40 is 1

4. Logical operators

The operators that are used to combine two or more relational expression are called as logical
operator.

These operators are used to perform logical operations on the given expressions.

There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).

 Logical AND
- It is denoted by &&

Dr. Shobha N, Assistant Prof., CSD 15


Introduction to C Programming DSCE

- It returns true when both conditions are true


- Example: (x>5) && (y<5)

 Logical OR
- It is denoted by ||
- It returns true when at-least one of the condition is true
- Example: (x>=10) || (y>=10)

 Logical NOT
- It is denoted by !
- it can be true or false
‘C’ programming Example:-

#include <stdio.h>
void main( )
{
int m=40,n=20;
int o=20,p=30;

if (m>n && m !=0)


{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \
"But, status is inverted as false\n");
}
}

Output:
&& Operator: Both conditions are true
|| Operator: Only one condition is true
! Operator: Both conditions are true. But, status is inverted as false

Dr. Shobha N, Assistant Prof., CSD 16


Introduction to C Programming DSCE

5. Bit wise operators

These operators are used to perform bit operations. Bit wise operators in C language are,

Operator precedence

& (bitwise AND) 1


| (bitwise OR) 2
~ (bitwise negate) 2
^ (XOR) 3
<< (left shift) 4
>> (right shift) 5

#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;

// The result is 00000001

printf("a = %d, b = %d\n", a, b);


printf("a&b = %d\n", a & b);

// The result is 00001101


printf("a|b = %d\n", a | b);

// The result is 00001100


printf("a^b = %d\n", a ^ b);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

return 0;
}

Dr. Shobha N, Assistant Prof., CSD 17


Introduction to C Programming DSCE

 Bitwise AND
- Denoted by &
- If corresponding bit positions in both the operands are one then result is one else result is
zero.

x y x|y x^y x&y


0 0 0 0 0
0 1 1 1 0
1 0 1 1 0
1 1 1 0 1

‘C’ programming Example:-


#include <stdio.h>
void main( )
{
int a,b,c;
a=10;
b=6;
c=a&b;
printf(“%d”,c);
}

Output:- 2

 Bitwise OR
- Denoted by |
- If corresponding bit positions in both the operands are zero then result is one .

In above same program


C=a|b
Output:-13

 Bitwise X-OR
- Denoted by ^
- If corresponding bit positions in both the operands are different then result is one .
In above same program
C=a^b
Output:-12

Dr. Shobha N, Assistant Prof., CSD 18


Introduction to C Programming DSCE

Bitwise left shift and Bitwise right shift refer class notes.

6. Conditional operators (ternary operators)

Conditional operators return Exp1 if condition is true and returns exp2 if condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true value: false value);
OR
(Condition? Exp1: Exp2);

Example: (A > 100? 1: 0);


.
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.

‘C’ programming Example:-


int main()

int a, b, big;

printf("Enter 2 numbers\n");

scanf("%d%d", &a, &b);

(a > b) ? (big = a) : (big = b);

printf("Biggest of two numbers is %d\n", big);

return 0;

#include <stdio.h>

int main()

int a, b, c, big;

Dr. Shobha N, Assistant Prof., CSD 19


Introduction to C Programming DSCE

printf("Enter 3 numbers\n");

scanf("%d%d%d", &a, &b, &c);

big=(a > b) ? (a>c?a:c) : (b>c?b:c);

printf("Biggest of three numbers is %d\n", big);

return 0;

7. Increment/decrement operators

Increment operators are used to increase the value of the variable by one and decrement operators
are used to decrease the value of the variable by one in C programs.

Syntax:

Increment operator ++i; (or) var_name++;


Decrement operator : – - j; (or) var_name – -;

[Link] Operator type Operator Description


++i
1 Pre increment Value of i is incremented before assigning it to variable i.
i++
2 Post-increment Value of i is incremented after assigning it to variable i.
– –i
3 Pre decrement Value of i is decremented before assigning it to variable i.
i– –
4 Post_decrement Value of i is decremented after assigning it to variable i.

#include <stdio.h>

int main()
{
int a=5, b=10;

printf("\n the value of variable %d is %d", ++a, a);


printf("\n the value of variable %d is %d", b++, b);

return 0;

Dr. Shobha N, Assistant Prof., CSD 20


Introduction to C Programming DSCE

8. Special operators
8.1 Comma operator:-
- It is denoted by ,
- If int a,b,c here , is used as operator instead of delimiter to separate the variables
- Comma operator has least precedence among all operators.

8.2 Sizeof () operator


- Even if it looks as function call, but it an operator.
- It is used to find the memory space allocated for each C data types.

‘C’ programming Example:-

#include <stdio.h> Storage size for int data type:4


void main() Storage size for char data type:1
{ Storage size for float data type:4
int a;
Storage size for double data type:8
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));

Q. what are the basic/simple/primitive data type in ‘c’?


Data Types:
A data types defines the type of data stored in memory location.
Data type determines how much memory should allocate for a variable.

There are basically two types of data types:


1. Fundamental/basic
2. Derived

Fundamental data types:

The fundamental data types are int, float double,and char

Dr. Shobha N, Assistant Prof., CSD 21


Introduction to C Programming DSCE

 int
Keyword int is used for declaring the variable with integer type. For example: int j

Here, j is a variable of type integer.

Type Storage size


int 2 or 4 bytes
unsigned int 2 or 4 bytes
Short 2 bytes
unsigned short 2 bytes
Long 4 bytes
unsigned long 4 bytes

 float

Variables of floating types can hold real values (with decimal) such as: 2.34, -9.382 etc. Keywords
either float or double is used for declaring floating type variable. For example:

float i ;

double j ;

Type Storage size


Float 4 byte
Double 8 byte
long double 10 byte

Note: Precision describes the number of significant decimal places that a floating value carries.

 char
Keyword char is used for declaring the variable of character type. For example:

char ch =’x’;

Dr. Shobha N, Assistant Prof., CSD 22


Introduction to C Programming DSCE

Type Storage size


Char 1 byte
unsigned char 1 byte
signed char 1 byte

Q. what is formatted and unformatted input/output in ‘c’?


‘c’ language provides several input /output function that can perform input, output operation.
These functions are collectively known as input/output library. They are divided into 2 ways
1. Formatted input/output
2. Unformatted input/output

1. Formatted input/output
Formatted input/output functions enables the user to specify the types of data and the way
in which it should takes input and print output. These are printf( ) and scanf( )

printf( ) function : -
The printf function is used to display the value to the output devices. It moves data from the
computer’s memory to the standard output devices.

Syntax: printf(“format specifier” , arg1, arg2, ….arg n );

Any string will be written in double quotes. arg 1. arg 2 variables or values

Format specifier:
Format specifiers are the character string with % sign followed with a character. It specifies the
type of data that is being processed.

%d int
%f float
%c char
%s string
%lf double
%ld long int

%u unsigned int
%h short integer
%o an octal integer
%x a hexadecimal integer

Dr. Shobha N, Assistant Prof., CSD 23


Introduction to C Programming DSCE

scanf( ) function : -

scanf function:
The scanf function gets data from the standard input device and stores it in the computer memory.

Syntax: scanf(“ format specifier”, & arg1, & arg2,…….,& argn ) ;

Format specifier is the control string to denote the data type of variable
& arg1, & arg2,…….,& argnı are the variables which stores values.

Dr. Shobha N, Assistant Prof., CSD 24

You might also like