Anda di halaman 1dari 17

C Intro:

Program: A group of instructions would be combined later on to form a program,


written to perform a specified task on a computer.

Programming: programming is a process that leads from an original formulation


of a computing problem to executable computer programs.

The act of writing a program is called Programming.

Language: It is media through which two object can communicate.

Programming Language: A programming language is a formal constructed


language designed to communicate instructions to a machine, particularly a
computer.

Type of Languages:
High Level Language: High-level language is any programming language that
enables development of a program in much simpler programming context and is
generally independent of the computer’s hardware architecture.

High–level language must be translated into machine language by a compiler or


interpreter

Ex. C, C++, FORTRAN, BASIC (Beginner’s All-purpose Symbolic Instruction Code)

Low Level Language: Low-level programming language is a programming


languages that provides little or no abstraction from a computer’s instruction set
architecture.

Ex. Machine level language or assembly language.

Important aspects of choose any language:

1. The way it stores data


2. The way it operates upon this data
3. How it accomplishes or achieve input and output and
4. How it lets you control the sequence of execution of instructions in a
program.
What is C ?
C is a programming language and developed at AT & T’s Bell Laboratories
of USA in 1972. It was designed and written by a man named Dennis Ritchie
(Father of C).

In the late seventies C began to replace the more familiar languages of that time
like PL/I, ALGOL, etc.

Why C seems so popular?

Reasons for still C is Important:

1. Major parts of popular operating systems like Windows, UNIX, Linux is still
written in C.
2. Device driver programs are exclusively written in C.
3. Mobile devices, tablets, common consumer devices like microwave oven,
washing machines and digital cameras, these smart devices comes from a
microprocessor, an operating system and a program embedded in this
devices.

C is the language of choice while building embedded operating


systems and programs.

4. Many popular gaming frameworks (like DirectX) have been built using C
language.
5. To interact with the hardware devices C only the choice.
Fundamentals of C:
C is language consist of characters, keywords, Instructions and Programs.

C Character Set:

A character denotes any alphabet, digit or special symbol used to represent


information.

Alphabets Upper case A, B, ….., Y, Z


Lower case a, b, ……, y, z
Digits All decimal digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols , comma, . period, :semicolon, : colon, ? question mark,
! exclamation mark, | vertical bar, / slash, \ backslash,
~ tilde, _ under score, ( left parenthesis, )right parenthesis
[ left parenthesis, ] right parenthesis, { left brace, } right
brace, #number sign or Hash sign, $ dollar sign, % percent
sign, & ampersand, ^ caret, * asterisk, - minus Sign, + plus
sign, < opening angle bracket (or less than sign), > closing
angle bracket, (or greater than sign)
White space blank space, new line, horizontal tab, carriage return and
Characters form feed

Constants, Variables and Keywords:

The alphabets, numbers and special symbols when properly combined form
constants, variables and keywords.
C Identifiers:

Identifier refers to name given to entities such as variables, functions, structures


etc.

Identifier must be unique. They are created to give unique name to an


entity to identify it during the execution of the program.

For example: int money;

double accountBalance;

Rules for naming an identifier:

1. Identifies must consist of only alphabets, digits or underscore symbol


2. First character must be alphabet or underscore(_)
3. Name of identifier cannot be any keyword.
4. Name of identifier is case sensitive i.e. value and Value are two different
variables
5. There is no rule on length of an identifier. However, the first 31 characters
of identifiers are easily understand by the compiler.
6. Special Characters are not allowed in identifier name.

C Keywords:
1. Keywords are predefined, reserved words used in programming that have
special meanings to the compiler.
2. Keywords are part of the syntax and they cannot be used as an identifier.
3. As C is a case sensitive language, all the keywords are written in lower case
letters.

For example: int money;

4. There are total 32 keywords present in according to ANSI C.


They are:

auto,double, int, struct, break, else, long, switch, case, enum, register,
typedef, char, extern, return, union, continue, for, signed, void, do, if,
static, while, default, goto, sizeof, volatile, const, float, short, unsigned

C Variables:

1. Variables are named memory locations used to hold some data of particular
type.
2. The value of a variable may change during the program execution at
different time, but it can contain a single value at a time.
3. Naming a variable will follow the rules of identifies
4. Declaration of a variable must be done before they are used in the C
Program. If you declare a variable in C, that means you are asking to the
OS for reserve a piece of memory with that variable name.
Declaration of a Variable:
1. It gives the information about the variable to the compiler.
2. What type of data will be kept in variable is specified in the variable
declaration.
3. When we declare a variable some space is allocation in in the main
memory(RAM) depending upon the type of datatypes
Syntax: datatype variable_name;
Example: int num;
Initialization of Variable:
1. Assignment of some value to the variable is known as initialization.
2. Before the assignment the variable contains one default value
Syntax: data_type variable_name;

variable_name = value;

Example: int x;

x = 50;

Note: Declaration and initialization can be done at same time.

Example: int num=20;

Types of C Variable:

There are three types of variables in c program. They are,

1. Local variable
2. Global variable
3. Environment variable

Local variable in c:

A. The scope of local variables will be within the function only.


B. These variables are declared within the function and can’t be accessed
outside the function.

Global variable in c:

A. The scope of global variables will be throughout the program. These


variables can be accessed from anywhere in the program.
B. This variable is defined outside the main function. So that, this variable is
visible to main function and all other sub functions.
Constants/Literals:

A constant is a value or an identifier whose value cannot be changed.

Types of C Constants:

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.
D. If no sign precedes an integer constant it is assumed to be positive.
E. No commas or blanks are allowed within an integer constant.
F. The allowable range for integer constants is -32768 to 32767.

Note: Truly speaking the range of an Integer constant depends upon the
compiler.

Rules for Constructing Real Constants or Floating Point constants:

These could be written in two forms—Fractional form and Exponential form.

For fractional form:

A. A real constant must have at least one digit.


B. It must have a decimal point.
C. It could be either positive or negative.
D. Default sign is positive.
E. No commas or blanks are allowed within a real constant.
Ex.: +325.34

In exponential form of representation, the real constant is represented in two


parts. The part appearing before ‘e’ is called mantissa, whereas the part
following ‘e’ is called exponent.

For exponential form:

A. The mantissa part and the exponential part should be separated by a letter
e.
B. The mantissa part may have a positive or negative sign.
C. Default sign of mantissa part is positive.
D. The exponent must have at least one digit, which must be a positive or
negative integer. Default sign is positive.
E. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Ex.: +3.2e-5

Rules for Constructing Character Constants:

A. A character constant is a single alphabet, a single digit or a single special


symbol enclosed within single inverted commas.
B. Both the inverted commas should point to the left. For example, ’A’ is a
valid character constant whereas ‘A’ is not.
C. The maximum length of a character constant can be 1 character.

Ex.: 'A'

Escape Sequences:

Escape Sequences are necessary to use characters which cannot be typed or has
special meaning in C programming. For example: newline (enter), tab, question
mark etc. In order to use these characters, escape sequence is used.

For example: \n is used for newline. The backslash ( \ ) causes "escape"


from the normal way the characters are interpreted by the compiler.

Escape Sequences:
Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
Structure of C program:

1. Documentation Section: in this Section we define comment like program


definition, name of programmer, etc..

Ex: /* */, //

2. Link Section: This Section is the core part of the programme in which
compiler links the inbuilt function from the system library.

Ex: # include < Library Name>

3. Definition Section: In this part, we define a symbolic constant.

Ex: define PI = 3.14

4. Global Declaration: When programmer wants to use some variables that


are used in more than one functions at a time or at that time.

Note: These 4 sections are optional.

5. main Section: This section contains two parts.

Declaration part: In which all the variables and user defined functions (udf)
are declared.

Execution part: In which program logic and other process is done.

6. Subprogram Section: It describes all the user defined functions (UDF) that
are called in main section.

Rules for writing all C programs:

1. Each instruction in a C program is written as a separate statement.


Therefore a complete C program would comprise of a series of statements.
2. 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.
3. 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.
4. All statements are entered in small case letters.
5. 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.
6. Every C statement must end with a ; Thus ; acts as a statement terminator.

Let us now write down our first C program for simply calculate simple interest.

/* Calculation of simple interest */

/* Author gekay Date: 25/05/2004 */

main( )

int p, n ;

float r, si ;

p = 1000, n = 3, r = 8.5 ;

si = p * n * r / 100 ; /* formula for simple interest */

printf ( "%f" , si ) ;

C operators:

1. C operators are symbols that are used to perform mathematical or logical


manipulations.
2. C programming language is rich with built-in operators.
3. Operators are used in programs to manipulate data and variables.

C operators can be classified into following types:

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Conditional operators
7. Special operators

Arithmetic operators:

Arithmetic Operators are used to performing mathematical calculations.C supports


all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator - increases integer value by one
-- Decrement operator - decreases integer value by one

Relational operators:

Relational operators are used to compare two quantities or values.

The following table shows all relation operators supported by C.

Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

Logical operators:

C provides three logical operators when we test more than one condition to make
decisions.

C language supports following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example


&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

Bitwise operators:

Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied to float
or double.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now let’s see truth table for bitwise &, | and ^

a b a&b a|b a^b


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

The bitwise shift operator, shifts the bit value. The left operand specifies the
value to be shifted and the right operand specifies the number of positions that
the bits in the value have to be shifted. Both operands have the same precedence.

Example: a = 0001000

b=2

a << b = 0100000

a >> b = 0000010

Assignment Operators:

1. Assignment operators applied to assign the result of an expression to a


variable.
2. C has a collection of shorthand assignment operators.

Operator Description Example


= assigns values from right side operands a=b
to left side operand
+= adds right operand to the left operand a+=b is same as a=a+b
and assign the result to left
-= subtracts right operand from the left a-=b is same as a=a-b
operand and assign the result to left
operand
*= multiply left operand with the right a*=b is same as a=a*b
operand and assign the result to left
operand
/= divides left operand with the right a/=b is same as a=a/b
operand and assign the result to left
operand
%= calculate modulus using two operands a%=b is same as
and assign the result to left operand a=a%b
Conditional operator:

C offers a ternary operator which is the conditional operator (?: in combination) to


construct conditional expressions.

? : Operator

It is actually the if condition that we use in C language decision making, but using
conditional operator, we turn the if condition statement into a short and simple
operator.

Syntax: conditional Expression ? expression 1 : expression 2

Explanation:

1. The question mark "?" in the syntax represents the if part.


2. The first expression (expression 1) generally returns either true or false,
based on which it is decided whether (expression 2) will be executed or
(expression 3)
3. If (expression 1) returns true then the expression on the left side of " : " i.e
(expression 2) is executed.
4. If (expression 1) returns false then the expression on the right side of " : "
i.e (expression 3) is executed.

Special operator:

Operator Description Example


sizeof Returns the size of an variable sizeof(x) return size of the
variable x
& Returns the address of an variable &x ; return address of the
variable x
* Pointer to a variable *x ; will be pointer to a variable
x

Data Types:
Data types simply refers to the type and size of data associated with variables and
functions.

C Data Types are used to:

1. Identify the type of a variable when it declared.


2. Identify the type of the return value of a function.
3. Identify the type of a parameter expected by a function

Types of data types:

Primary (Built-in) Data Types: void, int, char, double and float.

Derived Data Types: Array, References, and Pointers.

User Defined Data Types: Structure, Union, and Enumeration.


Integer type: Integers are used to store whole numbers without fractional part.

Type Size (bytes) Range:


int or signed int 2 or 4 -32,768 to 32767
unsigned int 2 or 4 0 to 65535
short or signed short 2 -128 to 127
unsigned short 2 0 to 255
long or signed long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295

Character type: Character types are used to store characters value.

Size and range:

Type Size(bytes) Range


char or signed char 1 -128 to 127
unsigned char 1 0 to 255

Floating point type: Floating types are used to store real numbers.

Size and range:


Type Size(bytes) Range Precision
Float 4 3.4E-38 to 3.4E+38 6 decimal places
double 8 1.7E-308 to 1.7E+308 15 decimal places
long double 10 3.4E-4932 to 1.1E+4932

void type:

1. The data type void actually refers to an object that does not have a value of
any type.
2. Void is an empty data type associated with functions and pointers
3. It is also known as generic data type
4. Its size is unknown, that’s why it is not used with variables
5. When void is used before a function it means that, the function will not
return anything to the calling function.
6. void main() : It says that main function will not return anything to the
operating system
7. If void is specified in the function argument, it explicitly says that the
function will not take any arguments.
Control Statements:

Conditional Statements or Decision making:

Decision making is used to specify the order in which statements are


executed based on conditions.

C language handles decision-making by supporting the following statements,

1. if statement
2. switch statement
3. conditional operator statement (? : operator)
4. goto statement

if statement:

The if statement may be implemented in different forms depending on the


complexity of conditions to be tested. The different forms are,

1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. Using else if statement

Decision control Syntax Description:


statements
if if (condition) In these type of statements, if
{ Statements; } condition is true, then respective
block of code is executed.
if…else if (condition) { In these type of statements,
Statement1; group of statements are executed
Statement2; } when condition is true. If
else { condition is false, then else part
Statement3; statements are executed.
Statement4; }
nested if if (condition1){ If condition 1 is false, then
Statement1; } condition 2 is checked and
else_if(condition2) statements are executed if it is
{ Statement2; } true. If condition 2 also gets
else Statement 3; failure, then else part is
executed.
else if if(expression1) { The expression is tested from the
statement block1; top(of the ladder) downwards. As
} soon as a true condition is found,
else if(expression2) { the statement associated with it
statement block2; is executed.
}
else
default statement;

switch statement:

switch statement is used when you have multiple possibilities for the if statement.

Syntax: switch(variable) {

case 1:

//execute your code

break;

case n:

//execute your code

break;

default:

//execute your code

break;

Points to Remember:

1. We don't use those expressions to evaluate switch case, which may return
floating point values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use
break after each block, but if you do not use it, then all the consecutive
blocks of code will get executed after the matching block.

Ex: int i = 1;

switch(i)

{
case 1:

printf("A"); // No break

case 2:

printf("B"); // No break

case 3:

printf("C");

break;

o/p: A B C

here the output was supposed to be only A because only the first case matches,
but as there is no break statement after that block, the next blocks are executed
too, until it a break statement in encountered or the execution reaches the end of
the switch block.

3. default case is executed when none of the mentioned case matches the
switch expression. The default case can be placed anywhere in the switch
case. Even if we don't include the default case, switch statement works.
4. Nesting of switch statements are allowed, which means you can have switch
statements inside another switch block. However, nested switch statements
should be avoided as it makes the program more complex and less
readable.

Note:

1. The expression is evaluated first inside the switch resulting a value.


2. If the value matches with the case value, statements under that case are
evaluated and the subsequent cases is also evaluated
3. The case value must be integer or character
4. case level must be different
5. case and default can be used in any order
6. default is optional case which executed when non of the case value matches
with the expression value

Goto:

The goto statement is used to alter the normal sequence of a C program.

Syntax: goto label;

... .. ...

... .. ...

... .. ...
label:

statement;

Here the label is an identifier. When goto statement is encountered, control of the
program jumps to label: and starts executing the code.

Arrays:

An array is a collection of similar type of data items (elements).

The data type of the elements may be any valid data type like char, int or float.
The elements of array have same variable name but each element has a different
index number (subscript).

Arrays can be single dimensional or multidimensional. The number of subscripts


determines the dimensional of array.

A one-dimensional array has one subscript, two dimensional array has two
subscripts and so on.

The one-dimensional arrays are known as vectors and two-dimensional arrays are
known as matrices.

Arrays should also be declared before they are used in the program.

The size and type of arrays cannot be changed after its declaration.

Syntax: data_type array_name[array_size];

Ex: float mark[5];

Here, we declared an array, mark, of floating-point data type and size 5.


Meaning, it can hold 5 floating-point values.

Anda mungkin juga menyukai