0% found this document useful (0 votes)
10 views75 pages

Unit2CPROGRAMMINGBASICSpdf 2024 09 09 13 51 30

This document provides an overview of C programming basics, including its definition, history, advantages, and structure of a C program. It covers fundamental concepts such as constants, variables, data types, and keywords, as well as the use of functions like printf() and scanf(). Additionally, it explains the types of variables, operators, and the importance of comments in C programming.

Uploaded by

sanghaniutsav65
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)
10 views75 pages

Unit2CPROGRAMMINGBASICSpdf 2024 09 09 13 51 30

This document provides an overview of C programming basics, including its definition, history, advantages, and structure of a C program. It covers fundamental concepts such as constants, variables, data types, and keywords, as well as the use of functions like printf() and scanf(). Additionally, it explains the types of variables, operators, and the importance of comments in C programming.

Uploaded by

sanghaniutsav65
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/ 75

Department of CE

Computer Programming Unit- 2

(01CE1101)
C Programming Basics

Prof. Reshma Sunil


• It is a Process to give a step by step instructions to
computer to do something(Operations).
• C is a general-purpose programming language
that is extremely popular, simple, and flexible to
What is use.
Programming? • It is also a structured programming language
that is machine-independent and extensively.
• It used to write various applications - Operating
Systems like Windows, and complex programs
like Oracle database, Git, Python interpreter,
Google, Mozilla Firefox, Compilers, Gaming and
animation software, etc.
History of C
 Robust Language
 Built-in-Functions
 Well Structured Programming Language
Advantages  Combine assembly language with High-Level
of C Language
 Efficient and Fast
 Highly Portable
 Ability to extend
Structure of
C Program
Documentation section:
The documentation section consists of a set of
comment lines giving the name of the program, the
author and other details, which the programmer
would like to use later.
Link section:
Structure of
The link section provides instructions to the
C Program compiler to link functions from the system library
such as using the #include directive.
Definition section:
The definition section defines all symbolic
constants such using the #define directive.
Global declaration section:
 There are some variables that are used in more than
one function.
Structure of  Such variables are called global variables and are
C Program declared in the global declaration section that is
outside of all the functions. This section also
declares all the user-defined functions.
main () function section:
 Every C program must have one main function
section. This section contains two parts;
i)Declaration part: The declaration part declares all
the variables used in the executable part.
ii)Executable part: There is at least one
statement in the executable part.
Structure of
 These two parts must appear between the opening
C Program and closing braces. The program execution begins
at the opening brace and ends at the closing brace.
 The closing brace of the main function is the logical
end of the program.
 All statements in the declaration and executable
part end with a semicolon.
Subprogram section:
 If the program is a multi-function program, then
the subprogram section contains all the user-
Structure of defined functions that are called in the main ()
C Program function.
 User-defined functions are generally placed
immediately after the main () function, although
they may appear in any order.
Example
/* Description: Writes the words "Hello, World!" on
the screen */
#include<stdio.h>
Simple C
int main()
Program
{
printf("Hello, World!\n");
return 0;
}
 #include<stdio.h> - stdio is standard for
input/output, this allows us to use some
commands which includes a file called stdio.h or
 This is a pre - processor command. That notifies
the compiler to include the header file stdio.h in
Points to the program before compiling the source-code.
remember  Two curly brackets "{...}" are used to group all
statements. Curly braces which shows how much
the main() function has its scope.
 \n – New line character. It indicates the complier
to display the output in new line.
Steps of Program Execution

Compilation 010100011010
101011100000
and 101010101010
Linking 001110101010

processes
 Creating program and save a file
 Compiling the program
Steps of
Program  Linking the program - with functions that
are needed from c library.
Execution
 Executing the program
Output:
#include<stdio.h>
void main() Hello World..
{
printf(“Hello World..”);
Example
}
#include<stdio.h> Output:
void main()
Example { Hello World..How are you?

printf(“Hello World..”);
printf(“How are you?”);
}
Output:
#include<stdio.h>
void main()
Example {
Hello World..
How are you?
printf(“Hello World..”);
printf(“\nHow are you?”);
}
 C does not contain any instruction to display output
on the screen.
 All output to screen is achieved using readymade
printf( ) library functions - printf( ).
and
The general form of printf( ) function is,
its Purpose  To display message
printf ( “Display strings”) ;
 To print the value
printf ( "<format string>", <list of variables>) ;
 The scanf() function is used for input. It reads the
input data from the console.
scanf("format Specifier”,&Variablename );
 Note the use of ampersand (&) before the
scanf( ) variables in the scanf( ) function is a must.
and scanf(“%d”, &a);
its Purpose  & is an ‘Address of’ operator. It gives the location
number (address) used by the variable in memory.
 When we say &a, we are telling scanf( ) at which
memory location should it store the value supplied
by the user from the keyboard.
 You need to use format specifiers whether you're printing
formatted output with printf() or accepting input with
scanf().
 The format specifier is used during input and output.
 It is a way to tell the compiler what type of data is in a
variable during taking input using scanf() or printing using
Format printf(). The following specifiers are used in C.
specifiers  Character format specifier : %c
in C  For Integer & Signed Integer format specifier : %d, %i
 Floating-point format specifier : %f, %e or %E
 String printing: %s
 Double floating-point number : %lf
 Unsigned integer: %u
 Long long int: 2.%lld
 Comments are used in a C program to clarify either
the purpose of the program or the purpose of some
statement in the program.
Comments  It is a good practice to begin a program with a
in a comment indicating the purpose of the program, its
author and the date on which the program was
C Program written.
 2 comment lines
- Single comment (//)
- Multiple line comment(/*…………*/)
Steps in
learning C
language
 A character denotes any alphabet, digit or special
symbol used to represent information.

The C
Character Set

Constants, Variables and Keywords


 The alphabets, digits and special symbols when
properly combined form constants, variables and
keywords.
 Constant is a any value that cannot be changed during
program execution.
 Example:

Constants 3.25 “Hello” ‘A’


‘b’ -20 ‘R’
98 78.354
“How are you?”
 Integer Constants
Types  Floating-point Constants
of
Constants  Character Constants
 String Constants
 It consists a sequence of digits.
 Rules for Constructing Integer Constants
(a) An integer constant must have at least one digit.
(b) It must not have a decimal point.
(c) It can be either positive or negative.
Integer (d) If no sign precedes an integer constant, it is
Constants assumed to be positive.
(e) No commas or blanks are allowed within an
integer constant.
(f) The allowable range for integer constants is
-2147483648 to +2147483647.
Types of Decimal -> 123, -321, 67945, +34
Integer
Octal -> 0463, 0, 0551
constants
Hexadecimal -> 0x8F,0x2,0Xbcd
 Floating Point constants are often called Real
constants.
 These represent numbers containing fractional
parts.
Floating point  This constants could be written in two forms —
 Fractional form
Constants  Exponential form
 Example: 2.36
-97.2354
Following rules must be observed while
constructing floating point constants
(a) A real constant must have at least one digit.
Floating point (b) It must have a decimal point.
Constants (c) It could be either positive or negative.
(d) Default sign is positive.
(e) No commas or blanks are allowed within a
real constant.
 These are represent a single character value.
 Example: ‘A’ ,’b’, ’@’
Rules for Constructing Character Constants
Character  A character constant is a single alphabet, a single
Constants 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.
• A sequence of characters which are
enclosed in double quotes.
String • Example: “Computer”
Constants “12345”
 It is used to store values in program.
 A particular type of variable can hold only the same
type of constant.
Variables  The value of the variable can be change during the
execution.
 Example:
X, balance, User_name
 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 ( _ ).
Rules  No commas or blanks are allowed within a
for variable name.
Variables  No special symbol other than an underscore (as
in gross_sal) can be used in a variable name.
 Uppercase and lowercase are
significant(different).
 Any variable used in the program must be
declared before using it.
Variables and  For example,
their Usage  int p, n ; //declaration
 float r, si ; //declaration
 si = p * n * r / 100 ; //usage
 how you can create or declare a new variable in the C
language,
data_type var_name;
(or)
data_type var_name1,var_name2…,var_name n ;
Variable
 where, data_type is a valid data type (along with
Declaration datatype modifiers, if required) and var_name is the
name of the variable.
 Example
int marks;
int enroll,contact_no;
 Once we have declared or created the variable,
then we can assign a value to it. This is called
variable definition.
Variable  // variable declaration
int marks;
definition
 // variable definition or variable Initialization
int marks = 10;
int i=0;
There are types of variables in c:

Types of 1.Local variable


Variables 2.Global variable
3.Static variable
 A variable that is declared with the static keyword is
called static variable.
 It retains its value between multiple function calls.
void function1()
Static Variable {
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
 A variable that is declared inside the function or
block is called a local variable.
 It must be declared at the start of the block.
void function1()
Local variable {
int x=10;//local variable
}
 You must have to initialize the local variable
before it is used.
 A variable that is declared outside the function
or block is called a global variable. Any function
can change the value of the global variable. It is
available to all the functions.
 It must be declared at the start of the block.
int value=20;//global variable
Global variable
void function1()
{
int x=10;//local variable
}
 All keywords are predefined, reserved words.
 Its having fixed meanings and meanings cannot be
C Keywords changed .
 The keywords cannot be used as variable names.
 There are 32 keywords available in C.
C Keywords
 A data type is a classification of data which tells
the compiler or interpreter how the programmer
intends to use the data.

 The type of a variable determines how much


Data types space it occupies in storage and how the bit
pattern stored is interpreted.

 Once we define a variable with some datatype


then we cannot change the datatype of that
variable.
Types Data Types

Primary(fundamental) Data Type int, char, float, double

Data types Derived Data Type array, pointer

User defined Data Type enum, structure, union

Void Data Type void


 C language supports 4 fundamental data types
Type Purpose Size Range of values
(Bytes
)
int For storing 2 or 4 -32768 to 32767
integers (for 2 bytes)
Data types float For storing 4 3.4e-38 to
real numbers 3.4e+38
double For storing 8 1.7e-308 to
double 1.7e+308
precision
floating
char for storing 1 -128 to 127
characters
 Some other data types :
Type Size Range of values
(Bytes)
short 2 -32768 to 32767
long 4 -2147483948 to 2147483947
Data types unsigned 1 0 to 255
char
unsigned 2 0 to 65535
int
unsigned 4 0 to 4294967295
long
 C Tokens are the smallest building block or smallest
unit of a C program.
C Tokens  The compiler breaks a program into the smallest
possible units and proceeds to the various stages of
the compilation, which is called token.
#include<stdio.h>
Tokens void main()
Example {
printf (“Hello World”) ;
}
C Tokens

C Tokens Keywords Constants Strings Operators

float -15.5 “ABC + -


while 100 ” = %
“year

Special
Identifiers
Symbols
main [ ]
amount {}
x ()
 Identifiers refers to the names of variables,
functions, and arrays.
 User defined names and consists of a sequence of
letters and digits, with a letter as first character.
Identifiers
 Ex:
int money;
double accountBalance;
 First character must be an alphabet (or
underscore).
 Must contain only letters, digits or underscore.
Rules for
defining  Only first 32 characters are significant.
identifiers  Cannot use a special keyword.
 Must not contain white space.
Operators as symbols that help us to perform
specific mathematical and logical computations on
operands.
 Arithmetic Operators
 Relational operators
Operators  Logical operators
in C  Assignment operator
 Increment and decrement operators
 Bitwise operator
 Conditional operators
 Special operators
 These are the operators used to perform
arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %).
 An operand is a term used to describe any object
that is capable of being manipulated.
 Arithmetic operator are of two types:
Arithmetic
Operators  Unary Operators: Operators that operates or
works with a single operand are unary operators.
For example: (+ , –)
 Binary Operators: Operators that operates or
works with two operands are binary operators. For
example: (+ , – , * , /)
Arithmetic
Operators
 These are used for comparison of the values of
two operands.
 For example, checking if one operand is equal to
the other operand or not, an operand is greater
than the other operand or not etc.
Relational ✓ Equal to operator ==
Operators ✓ Not equal to operator !=
✓ Greater than operator >
✓ Less than operator <
✓ Greater than or equal to operator >=
✓ Less than or equal to operator <=
 Logical Operators are used to combine two or
more conditions/constraints or to complement
the evaluation of the original condition in
consideration.
Logical  The result of the operation of a logical operator is
a boolean value either true or false.
operators
 Logical AND operator: The ‘&&’ operator returns
true when both the conditions under
consideration are satisfied. Otherwise it returns
false. For example, a && b returns true when both
a and b are true (i.e. non-zero).
 Logical OR operator: The ‘||’ operator returns true
even if one (or both) of the conditions under
consideration is satisfied. Otherwise it returns false.
For example, a || b returns true if one of a or b or
Logical both are true (i.e. non-zero). Of course, it returns
operators true when both a and b are true.

 Logical NOT operator: The ‘!’ operator returns true


the condition in consideration is not satisfied.
Otherwise it returns false. For example, !a returns
true if a is false, i.e. when a=0.
 Assignment operators are used to assign value to
a variable.
 The left side operand of the assignment operator
Assignment is a variable and right side operand of the
operators assignment operator is a value.
 The value on the right side must be of the same
data-type of variable on the left side otherwise
the compiler will raise an error.
Assignment
operators
 Increment and decrement operators are

 Increment ++
Increment  decrement - -
and  Both are used to change the value of an operand
decrement (constant or variable) by 1.
operators  Increment ++ increases the value by 1.
 decrement -- decreases the value by 1.
 These two operators are unary operators,
meaning they only operate on a single operand.
 The Bitwise operators is used to perform bit-level
operations on the operands.
 The operators are first converted to bit-level and
Bitwise then the calculation is performed on the
Operators operands.
 The mathematical operations such as addition,
subtraction, multiplication etc. can be performed
at bit-level for faster processing.
Bitwise
Operators
 The conditional operator in C is also
called the ternary operator because it operates on
three operands.
 The operands may be an expression, constants or
variables. It starts with a condition, hence it is
called a conditional operator.
Conditional Syntax:
operator expression1 ? expression2 : expression3;
or
condition ? true statement : false statement;
Example:
a=10; b=15;
X=(a>b)?a : b;
Special
Operators
 Operator precedence determines the grouping of
terms in an expression and decides how an
expression is evaluated.
 Certain operators have higher precedence than
Operator others.
Precedence  For example, the multiplication operator has a
and higher precedence than the addition operator.
Associativity  For example: Solve
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30
 Operators Associativity is used when two
operators of same precedence appear in an
expression. Associativity can be
either Left to Right or Right to Left.
 Operators with the highest precedence appear at
Operator the top of the table, those with the lowest appear
Precedence at the bottom. Within an expression, higher
and precedence operators will be evaluated first.
Associativity  For example:
‘*’ and ‘/’ have same precedence and their
associativity is Left to Right, so the expression “100 /
10 * 10” is treated as “(100 / 10) * 10”.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Operator Equality == != Left to right
Precedence Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= Right to left
|=
Comma , Left to right
Type conversion :
In type conversion, a data type is automatically converted
into another data type by a compiler at the compiler time. In
type conversion, the destination data type cannot be smaller
than the source data type, that’s why it is also called widening
Type conversion. One more important thing is that it can only be
applied to compatible data types.
Conversion
and Type Type Conversion example

Casting int x=30;

float y;

y=x; // y==30.000000.
#include <stdio.h>
int main ()
Type Casting - {
Example float x;
x = (float) 7/5;
printf(“%f”,x);
}
Type Casting
 In typing casting, a data type is converted into another
data type by the programmer using the casting
operator during the program design.
 The destination data type may be smaller than the
Type source data type when converting the data type to
another data type, that’s why it is also called narrowing
Conversion conversion.
and Type  Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
Casting
where
- (): is a casting operator.
- target_datatype: is a data type in which we want to
convert the source data type.
 Converting an expression of a given type into another type
is known as type casting. typecasting is more use in c
language programming. Here, It is best practice to convert
lower data type to higher data type to avoid data loss.
 Data will be truncated when the higher data type is
Type Casting – converted to lower. For example, if a float is converted to
Types int, data which is present after the decimal point will be
lost.
 There are two types of type casting in c language.
✓Implicit Conversion
✓Explicit Conversion
IMPLICIT CONVERSION
Implicit conversions do not require any operator for converted. They
are automatically performed when a value is copied to a compatible
type in the program.Here, the value of a has been promoted from int
to double and we have not had to specify any type-casting operator.
This is known as a standard conversion.
Example :
#include<stdio.h>
Type Casting – #include<conio.h>
Types void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(“implicit value is %d”,p);
getch();
}
EXPLICIT CONVERSION
In C language, Many conversions, especially those that imply a
different interpretation of the value, require an explicit
conversion. We have already seen two notations for explicit
type conversion.
Ex:
#include<stdio.h>
Type Casting – #include<conio.h>
Types void main()
{
int i=20;
short p;
clrscr();
p = (short) i; // Explicit conversion
printf(“Explicit value is %d”,p);
getch();
}
S.No TYPE CASTING TYPE CONVERSION
In type casting, a data type is
Whereas in type conversion, a data
converted into another data
1. type is converted into another data
type by a programmer using
type by a compiler.
casting operator.
Type Type casting can be applied Whereas type conversion can only
Conversion 2. to compatible data types as be applied to compatible
well as incompatible data types. datatypes.
and Type In type casting, casting
Casting 3.
operator is needed in order to Whereas in type conversion, there
cast the a data type to another is no need for a casting operator.
data type.
In typing casting, the
destination data type may be Whereas in type conversion, the
4. smaller than the source data destination data type can’t be
type, when converting the data smaller than source data type.
type to another data type.
S.NO TYPE CASTING TYPE CONVERSION
Type casting takes place during
Whereas type conversion is done
5. the program design by
at the compile time.
programmer.
Type
Conversion Type casting is also called Whereas type conversion is also
narrowing conversion because in called widening conversion
and Type 6. this, the destination data type because in this, the destination
Casting may be smaller than the source data type can not be smaller than
data type. the source data type.

Type casting is more efficient and Whereas type conversion is less


7.
reliable. efficient and less reliable.
Thank You!!

You might also like