0% found this document useful (0 votes)
62 views104 pages

Cprogram

This document provides an overview of the basic structure and components of a C program. It discusses the typical sections of a C program which include documentation, preprocessor directives, definitions, global declarations, the main function, and sub-programs. It also covers various C programming concepts such as data types, variables, constants, and input/output statements. The life cycle of a C program from writing the source code to generating the executable is also summarized.

Uploaded by

Hrithik Jerath
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)
62 views104 pages

Cprogram

This document provides an overview of the basic structure and components of a C program. It discusses the typical sections of a C program which include documentation, preprocessor directives, definitions, global declarations, the main function, and sub-programs. It also covers various C programming concepts such as data types, variables, constants, and input/output statements. The life cycle of a C program from writing the source code to generating the executable is also summarized.

Uploaded by

Hrithik Jerath
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
You are on page 1/ 104

COMPUTER

PROGRAMMING

Basics about C
program
Topics covered

- Structure of C Program
- Life Cycle of Program from Source code to
Executable
- Compiling and Executing C Code
- Keywords
- Identifiers
- Primitive Data types in C
- Variables
- Constants
- Input/Output statements in C
- Operators
- Type conversion and type casting
Structure of a C program
A C program is divided into different sections. There are
six main sections to a basic c program :
1. Documentation/ Comments Section
2. Preprocessor Directives/ Link Section
3. Definition Section
4. Global Declaration Section
5. Main Function
6. Sub-program Section
1. Document/ Comments Section
• The documentation section is the part of the program where the
programmer gives the details associated with the program.

• He usually gives- Name of the program,


- The Author And Other Details,
which the programmer would like to use later.

• Comment means explanations or annotations that are included in a


program for documentation and clarification purpose.

• Comments are completely ignored by the compiler during


compilation and have no effect on program execution.

• This section is optional


1. Documentation/ Comments Section
(cont..)
• Multiline Comments starts with ‘/*’ and ends with ‘*/’
• Single line comments starts with ‘//’

Example:
/* Comments Section
Structure of C Program
Author: XXXX
Date : 28/07/20
*/
// My first C Program
2. Link Section
• This part of the code is used to declare all the header files that
will be used in the program.
• This leads to the compiler being told to link the header files to
the system libraries.
• Example:
• #include<stdio.h>
• These are also called preprocessor directives.
• Preprocessor Directives are always preceded with ‘#’ sign .
• These are the first statement to be checked by the compiler.
• There are many preprocessor directives but most important is
#include <stdio.h>
2. Link Section (cont…)

#include<stdio.h>
• Tells the compiler to include the file stdio.h during
compilation
• ‘stdio.h’ stands for standard input output header
file and contains function prototype for input
output operations e.g. printf() for output and
scanf() for input, etc.
2. Link Section (cont…)
Other popular header files:

#include<string. h> (String header)


#include<stdlib. h> (Standard library header)
#include<math. h> (Math header )
3. Definition Section

• In this section, we define different constants. The


keyword define is used in this part.

• #define PI 3.14
4. Global Declaration Section
• The global variables that can be used anywhere in
the program are declared in global declaration
section.

• This section also declares the user defined functions.


• float area(float r);
• int a=7;
5. Main Function
• It is necessary to have one main() function section in every C
program.
• This section contains two parts, declaration and executable part.
• The declaration part declares all the variables that are used in
executable part.
• These two parts must be written in between the opening and
closing braces.
• Each statement in the declaration and executable part must end
with a semicolon (;).
• The execution of program starts at opening braces and ends at
closing braces.
Example of a C Program
6. Sub-program Section

• All the user-defined functions are defined in this section of the


program.
• User can define their own functions in this section which performs
particular task as per the user requirement. So user creates this
according to their needs.

Example:
int add(int a, int b)
{
return a+b;
}
Example of a C Program
//File Name: areaofcircle.c
// Author:XXX
// date: 01/10/2020
//description: a program to calculate area of circle
#include<stdio.h>//link section
#define pi 3.14;//definition section
float area(float r);//global declaration
int main()//main function
{
float r;
printf(" Enter the radius:n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}
float area(float r)
{
return pi * r * r;//sub program
}
Life Cycle of a C Program

Let us suppose, we write above program in


Notepad and save the file as simple.c
Life Cycle of a C Program
Preprocessor
Compiler
Assembler
Linker
Loader
Life Cycle of a C Program
C Character Set
C Character Set (Special Characters)
C Character Set (Special Characters)
• Each character is assigned a unique numeric value.
• These values put together are called character codes.
Delimiters
Keywords or reserved words

The following list shows the reserved words in C. You


cannot use them for variable names
Identifiers in C

C identifier is a name used to identify a variable,


function, or any other user-defined item.
An identifier starts with a letter A to Z, a to z, or an
underscore '_' followed by zero or more letters,
underscores, and digits (0 to 9).

C is a case-sensitive programming language.


Thus, Manpower and manpower are two different
identifiers in C.
Rules for forming Identifier Names
• It cannot include any special characters or
punctuation marks (like #, $, ^, ?, . , etc.)
except underscore ‘ _ ’

• There cannot be two successive underscores

• Keywords cannot be used as identifiers


• Case of alphabetic characters is significant
Rules for forming Identifier Names

• It can be of any reasonable length

• It can be mainly upto 63 characters long

• Underscore can be used to separate parts of


the name in an identifier
Data Types

Data types in C refer to an extensive system used for


declaring variables or functions of different types.
The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is
interpreted.

C supports a number of qualifiers that can be applied


to the basic data types e.g. short, long, unsigned and
signed etc.
Data Types
Primitive Data types in C
Primitive Data Types
Difference between short and long integers

Short Integer Long Integer


• 2 bytes in memory • 4 bytes in memory
• -32768 to +32767 • -2147483648 to +2147483647
• Program runs faster • Program runs slower
• %d or %i • %ld
• int or short int
• long or long int

When a variable is declared without short or long keyword, the default is short-
signed int
Difference between signed and unsigned integers

Short Signed Integer Short Unsigned Integer


• 2 bytes in memory • 2 bytes in memory
• -32768 to +32767 • 0 to 65535
• %d or %i
• %u
• long signed integers
(-2147483648 to • long unsigned int
+2147483647) ( 0 to 4294967295)
float and double

float double

• 4 bytes in memory • 8 bytes in memory


• 3.4e-38 to +3.4e+38 • 1.7e-308 to +1.7e+308
• %f • %lf
• float • double

long double 3.4e-4932 to 1.1e+4932 , takes 10 bytes in memory


Difference between signed and unsigned char

Signed Character Unsigned Character

• 1 byte in memory • 1 byte in memory


• -128 to +127 • 0 to 255
• %c • %c
• char • unsigned char

When printed using %d format specifier, it prints corresponding ASCII character


Variables
• Variable is a meaningful name given to the
data storage location in computer memory.
• When using variable, we actually refer to
address of the memory where the data is
stored.
• It can store one value at a time.
• Its value may be changed during the program
execution.
Variables
#include<stdio.h>
int main()
{ int a =10;
printf("%d",a);
return 0;
}
Rules for defining Variables
• It must begin with character or an underscore
without spaces.
• Length of variables varies from compiler to compiler.
However, ANSII standard recognizes max length of
variable up to 31 characters.
• Its name should not be a C keyword
• It can be a combination of upper and lower case.
• It should not start with a digit
• Blanks and commas are not permitted
Examples of Variables

• int emp_num;
• float salary;
• char grade;
• double balance_amount;
• unsigned short int velocity;
Initializing Variables

• int emp_num = 7;
• float salary = 1100.50;
• char grade = ‘A’;
• double balance_amount = 5000;
Constants
• A constant is an entity whose value does not
change during the execution of the program
Constants
• Declaration

const int var = 100;


Constants
#include<stdio.h>
int main()
{ const int a=10;
printf("%d",a);
a=20; // gives error you can't modify const
return 0;
}
Variables and constants
Input/ Output Statements
• C language supports two input/output functions
printf and scanf.
• printf is used to convert data stored in a program
into a text stream for output to the monitor.
• scanf is used to convert the text stream coming from
the keyboard to data values and stores them in
program variables.
printf()
• Print Formatting.
• Displays information required by the user.
• Prints values of the variables.
• Takes data values, converts them to text
stream using formatting functions specified in
a control string and passes resulting text
stream to standard output.
printf()
• The control string may contain zero or more
conversion specifications, textual data, and
control characters to be displayed.
• printf( “control string” , arg1, arg2………, argn);

• Control characters can also be included in


printf statement.

• \n , \t , \r , \a etc.
printf()
• printf("This is a message \n");

• How do we print the value of a variable?


int a = 22, b = 14;

• Answer: Use special format specifiers


depending on the type of the variable

• Format specifiers begin with % sign


scanf()
• Scan Formatting.
• Read formatted data from the keyboard.
• Takes text stream from the keyboard, extracts
and formats data from the stream according
to a format control string and then stores the
data in specified program variables.
scanf()
• scanf( “control string” , arg1, arg2………, argn);

• The control specifies type and format of data


obtained from the keyboard and stored in
memory locations pointed by the arguments.

• The arguments are actually variable addresses


where each piece of data are to be stored.

• Ignores blank spaces, tabs, newline


scanf()

#include <stdio.h>
int main()
{ int i ;
float x;
scanf(“%d%f”, &i, &x);
return 0;
}
Example
#include <stdio.h>
int main()
{
printf(“ \n Result: %d %c%f”, 12, ‘a’, 2.3);
return 0;
}

Result: 12a2.3
More I/O statements in C
Input: gets()
Output: puts()

main(){
char s[20]; //string is array of char
puts("Enter a string: "); gets(s);
puts("Here is your string"); puts(s);
}
C operators

• To build an expression, operators are used with


operands like 4 + 5, Here, 4 and 5 are operands and ‘+’
is operator

C contains following group of operators –


1) Arithmetic
2) Assignment
3) Logical/Relational
4) Bitwise
5) Miscellaneous
Arithmetic Operators

Pre increment/Decrement (++i or --i):


First increment/decrement current value by 1 and then use the
incremented/decremented value
Post increment/Decrement (i++ or i--):
First use the current value and then increment/decrement current value by 1 for next
time use
Arithmetic operators Example
#include<stdio.h>
void main()
{
int i=7,j=5;
printf(“%d %d %d %d \n”, i+j, i-j, i*j, i/j ); 12 2 35 1
printf(“%d \n”, i%j ); 2
printf(“%d %d \n”, i++, ++j ); 7 6
}
Assignment Operators
• Each expression contains two parts: lvalue and rvalue,
• Arithmetic operations are performed to calculate rvalue,
• Assignment operators are used to assign the rvalue to lvalue
Example:
i=i+1
can also be reduced to
i+=1
Assignment Operators Example
Relational Operators
A relational operator is a programming language construct
or operator that tests or defines some kind
of relation between two entities.

•If condition is true it returns 1 else returns 0.


Relational Operators (Cont..)
#include<stdio.h>
void main()
{
int i=7,j=1,k=0;
printf(“%d \n”,i==j); 0
printf(“%d \n”,i<j); 0
printf(“%d \n”,i>j); 1
printf(“%d \n”,i<=j); 0
printf(“%d \n”,i>=j); 1
printf(“%d \n”,i!=j); 1
}
Relational Operators (Cont..)
/* C program to find largest number using if...else statement */
#include <stdio.h>
int main()
{ float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a>=b) {
if(a>=c)
printf("Largest number = %f",a);
else
printf("Largest number = %f",c);
}
else {
if(b>=c)
printf("Largest number = %f",b);
else
printf("Largest number = %f",c);
}
return 0;
}
Logical Operators
• Allow a program to make a decision based on multiple
conditions.
• Each operand is considered a condition that can be evaluated to
a true or false value.
• Logical operator returns 0 or 1.
• The Logical operators are: &&, || and !
• op1 && op2-- Performs a logical AND of the two operands.
• op1 || op2-- Performs a logical OR of the two operands.
• !op1-- Performs a logical NOT of the operand.
• Op1 and op2 may be one condition or single operand
• C considers non-zero value to true and zero to false.
• Examples:(a>b)&&(a>c) , a&&b, 5&&8 etc.
Logical Operators
&&(Logical AND)
• The && operator is used to determine whether both
operands or conditions are true
• For example:
• a=50,b=9
• if (a == 10 && b == 9)
printf(“Hello!");
If either of the two conditions is false or incorrect, then
the printf command is bypassed.
Example of Logical operator

Output:
|| (Logical OR)
• The || operator is used to determine whether either of the condition is true.
• For example:
• a=50,b=9
• if (a== 10 || b == 9) // either of the condition should be true for printing hello!
printf(“Hello!");
If both of the two conditions are false, then only the printf command is bypassed.
Ex2: if(0||9)
printf(“Correct !”);
else
printf(“Incorrect !”);
Caution: If the first operand of the || operator evaluates to true, the second operand will
not be evaluated. This could be a source of bugs if you are not careful.
• For instance, in the following code fragment:
• if (9 || X++) {
• print(“X=%d\n“,X); } variable X will not be incremented because first condition is evaluates
to true.
|| (Logical OR)

Caution: If the first operand of the || operator evaluates to true,


the second operand will not be evaluated. This could be a
source of bugs if you are not careful.

For instance, in the following code fragment:


if (9 || X++) {
print(“X=%d\n“,X); }

variable X will not be incremented because first condition is


evaluates to true.
! (Logical NOT)
• The ! operator is used to convert true values to false and
false values to true. In other words, it inverts a value
• For example:
• a=50,b=9
• if (!(a== 10)) //
printf(“Hello!");

Ex2: if(!(0||9))
printf(“Correct !”);
else
printf(“Incorrect !”);
Bitwise Operators
•In the C programming language, operations can be performed on a bit
level using bitwise operators.
•Following are the bitwise Operators
Bitwise AND

•A bitwise AND takes two binary representations of equal length


and performs the logical AND operation on each pair of
corresponding bits.

The result in each position is 1 if the first bit


is 1
and the
second bit is 1; otherwise, the result is 0.

Example: a=5, b=3;


printf(“%d”,a&b); will print 1
0101--5
& 0011--3
0001--1
Bitwise AND

•& operation may be used to determine whether a particular bit is set (1)
or clear (0). For example,
•given a bit pattern 0011 (decimal 3), to determine whether the second bit
is set; we use a bitwise AND with a bit pattern containing 1 only in the
second bit:
• 0011 (decimal 3)
• & 0010 (decimal 2)
• 0010 (decimal 2)
Bitwise OR(|)

A bitwise OR takes two bit patterns of equal length and


performs the logical inclusive OR operation on each pair of
corresponding bits.

The result in each position is 1 if the first bit is 1 or the second


bit is 1 or both bits are 1; otherwise, the result is 0.

Example: a=5, b=3;


printf(“%d”,a|b);
will print 7
0101--5
| 0011--3
0111--7
Bitwise XOR(^)

A bitwise XOR(^) takes two bit patterns of equal length and


performs the logical exclusive OR operation on each pair of
corresponding bits.

The result in each position is 1 if only the first


bit is 1 or only the second bit is 1, but will be
0 if both are 0 or both are 1.

printf(“%d”,a^b); will print 6


0101--5
^ 0011--3
0110--6
Shift Operators

Left Shift Operator (<<):The left shift operator will shift the
bits towards left for the given number of times.

int a=2<<1; will print 4


Printf(“%d”,a);//

If you left shift like 2<<2, then it will give the result as 8.

Therefore left shifting n time, is equal to multiplying the


value by 2n.
Shift Operators
Right shift Operator ( >>)

The right shift operator will shift the bits towards right for the
given number of times

int b=4>>1 will print 2


printf(“%d”,b);//

Right shifting n time, is equivalent to dividing the value by 2n.


Bitwise Operators Example

o/p=>Turbo C++ 4.5


Miscellaneous Operators
• There are few other important operators
including sizeof and ? : supported by C Language.
Examples of sizeof()
#include <stdio.h>
main() {
int a = 4;
float b=50.45;
char c;
printf("Size of variable a = %d\n", sizeof(a) );
printf("Size of variable b = %d\n", sizeof(b) );
printf("Size of variable c= %d\n", sizeof(c) );
printf("Size of 233= %d\n", sizeof(233) );
printf("Size of 20.55= %d\n", sizeof(20.55) );
printf("Size of 'y'= %d\n", sizeof('y') );
printf("Size of unsigned int= %d\n", sizeof(unsigned int) );
}
Examples of conditional operator(Ternary
Operator)

main() {
int a , b,c;
a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );
c = (a == 10) ? 20: 30;
printf( "Value of c is %d\n", c );
}
WAP to check even or odd using
conditional operator
#include<stdio.h>
main() {
int n;
printf("Enter number n");
scanf("%d",&n);
(n%2 == 0) ? printf("%d is even",n): printf("%d is odd",n);
}
Operators available in C can be classified in
following ways:

1. unary – that requires only one operand.


For example: &a, ++a, *a ,--b etc.

2. binary - that requires two operands.


For example: a + b, a * b, a<<2

3. ternary - that requires three operands.


For example: (a>b) ? a : b [ ? : ]
Precedence and Associativity
•If more than one operators are involved in an expression then, C language has
predefined rule of priority of operators. This rule of priority of operators is called
operator precedence.

•Associativity indicates in which order two operators of same precedence


(priority) executes.
Examples of precedence of operators

•precedence of arithmetic operators(*,%,/,+,-) is higher than relational


operators(==,!=,>,<,>=,<=) and precedence of relational operator is higher
than logical operators(&&, || and !).
Example of Associativity of Operators

Example 1:
a==b!=c

Here, operators == and != have same precedence.

The associativity of both == and != is left to right, i.e, the


expression in left is executed first and execution take place
towards right.

Thus, a==b!=c equivalent to :

(a==b)!=c
Example of Associativity of Operators

Example 2:

Associativity is important, since it changes the meaning of an


expression. Consider the division operator with integer
arithmetic, which is left associative

4 / 2 / 3  (4 / 2) / 3  2 / 3 = 0

If it were right associative, it would evaluate to an undefined


expression, since you would divide by zero

4 / 2 / 3  4 / (2 / 3)  4 / 0 = undefined
What will be the value of i

i=2*3/4+4/4+8-2+5/8

i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +
Arithmetic expressions vs C expressions
•Although Arithmetic instructions look simple to use one often
commits mistakes in writing them.

•following points should keep in mind while writing C programs:


(a) C allows only one variable on left-hand side of = That is, z =k * l is
legal, whereas k * l = z is illegal.

(b)Other than division operator(/) C has modulus operator(%).


Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0.

• Note that 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.
Type Conversion & Type Casting

• Type conversion or type casting of variables refers to


changing a variable of one data type into another.

• Type conversion is done implicitly whereas,

• Type casting has to be done explicitly


Type Conversion
It is done when the expression has variables of
different data types.

To evaluate the expression,


the data type is promoted
from lower to higher level
where the hierarchy of data
types is given in the figure
Type Conversion
float x;
int y = 3;
x = y;

Output:
x = 3.000000
Type Conversion Example
#include <stdio.h>
main()
{ int number = 1;
char character = 'k';
int sum;
sum = number + character;
printf("Value of sum : %d\n", sum );
} OUTPUT
Value of sum :
10 8
Important regarding Type Conversion
• Type conversion is also called as implicit or standard type
conversion.

• We do not require any keyword or special statements in


implicit type casting.

• Converting from smaller data type into larger data type is


also called as type promotion.

• The type conversion always happens with the compatible


data types.
Important regarding Type Conversion

• Converting float to an int will truncate the fraction


part hence losing the meaning of the value.

• Converting double to float will round up the digits.

• Converting long int to int will cause dropping of


excess high order bits.
Type Casting

• Type casting is also known as forced conversion or


explicit type conversion

• It is done when the value of a higher data type has to


be converted into the value of a lower data type.

float salary = 10000.00;


int sal;
sal = (int) salary;
Type Casting
res = (int ) 9.5;

res = (int) 12.3 / (int) 4.2;

res = (double) total / n;

res = (int) a + b;

res = cos ( (double) x);


Thank You

You might also like