0% found this document useful (0 votes)
12 views

Unit 1 (C)

Uploaded by

Sakkthi Prabha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit 1 (C)

Uploaded by

Sakkthi Prabha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

C Programming

UNIT I

Introduction
► C programming is considered as the base for other programming languages.
► It is known as mother language.
► The C Language is developed by Dennis Ritchie for creating system
applications that directly interact with the hardware devices such as drivers,
kernels, etc.
► Mother language
► System programming language
► Procedure-oriented programming language
► Structured programming language
► Mid-level programming language[ it supports the feature of both low-level and
high-level languages.]
Features of C Language
► C is the widely used language. It provides many features that are given below.
► Simple and Efficient
► Machine Independent or Portable
► Mid-level programming language
► structured programming language
► Rich Library
► Memory Management
► Fast Speed
► Pointers
► Recursion
► Extensible
Example of a simple C Program

► #include <stdio.h>
► int main(){
► printf("Hello C Language");
► return 0;
► }
C Program Life Cycle

► Step 1: Writing code


► Step 2: Saving to file(.c extension is used)
► Step 3: Compilation
► Step 4: Linking object files
► Step 5: Output
Stages of Compilation
o Performed by a program called the compiler
o Translates the preprocessor-modified source code into object code
(machine code)
o Checks for syntax errors and warnings
o Saves the object code to a disk file
o If any compiler errors are received, no object code file will be
generated.
o An object code file will be generated if only warnings, not errors, are
received.

Execution:
► when the program become don’t has errors, the computer execute it to
produce the ……output.
Implement the algorithm
• Errors are of three types:
. syntax errors
. run-time errors
. logic errors

• Syntax errors: detected by the C compiler


▪ source code does not conform to one or more of C’s grammar rules
▪ Examples of syntax errors: undeclared variable, …
▪ Often one mistake leads to multiple error messages – can be confusing

Programming Fundamentals --> Ch1. Problem solving 7


Implement the algorithm
▪Run-timeerrors: detected and displayed by computer during
execution.
- Occur when program directs computer to perform illegal operation. Example: int x=y/0;
- will stop program execution and display message

• Logic errors.
- caused by faulty algorithm
- sign of error: incorrect program output
cure: thorough testing and comparison with expected results

A logic error is referred to as a bug, so finding logic errors is


called debugging.

Programming Fundamentals --> Ch1. Problem solving 8


C Tokens

► A token is the smallest unit used in a C program.


Each and every punctuation and word that you
come across in a C program is token. A compiler
breaks a C program into tokens and then
proceeds ahead to the next stages used in the
compilation process.
Types of Tokens in C

► Identifiers
► Keywords
► Operators
► Strings
► Special Characters
► Constant
Identifiers in C

► These are used to name the arrays, functions, structures,


variables, etc. The identifiers are user-defined words in the C
language. These can consist of lowercase letters, uppercase
letters, digits, or underscores, but the starting letter should always
be either an alphabet or an underscore. We cannot make use of
identifiers in the form of keywords
The rules that we must follow when
constructing the identifiers:
► The identifiers must not begin with a numerical digit.
► The first character used in an identifier should be either an underscore or an
alphabet. After that, any of the characters, underscores, or digits can follow it.
► Both- the lowercase and uppercase letters are distinct in an identifier. Thus, we
can safely say that an identifier is case-sensitive.
► We cannot use an identifier for representing the keywords.
► An identifier does not specify blank spaces or commas.
► The maximum length of an identifier is 31 characters.
► We must write identifiers in such a way that it is not only meaningful- but also
easy to read and short.
Keywords in C

► Keywords as the reserved or pre-defined words that hold their


own importance. It means that every keyword has a functionality
of its own. Since the keywords are basically predefined words
that the compilers use, thus we cannot use them as the names of
variables. If we use the keywords in the form of variable names, it
would mean that we assign a different meaning to it- something
that isn’t allowed.
► C language provides 32 keywords
S/N KEYWORDS MEANING
1 auto Used to define automatic storage class
2 break Used to terminate loop and switch statements
3 case Used to represent a case(options) in switch statement

4 char Used to define a character data type


5 const Used to define a constant variable
6 continue Used to skip a process in loop and pass control to the
beginning of the loop

7 default Used to represent a default case in switch statement

8 do Used to define a block in a do-while loop


9 double Used to define a floating double datatype

10 else Used as a fallback statement in if-else statement for a


falsy condition
S/N KEYWORDS MEANING

11 enum Used to define enumerated data type

12 extern Used to extend variable or function to another program


files

13 float Used to define a float data type

14 for Used to define a for-loop statement block

15 goto Used to jump statement in loop block

16 if Used to define a conditional if-else statement

17 int Used to define an integer variable

18 long Used to modify a basic data type

19 register Used to define register CPU variable

20 return Used to terminate function execution and return value to


the calling function
S/N KEYWORDS MEANING
21 short Used to modify a basic data type
22 signed Used to modify a basic data type
23 sizeof Used to ascertain the size of a variable type
24 static Used to define static variable
25 struct Used to define structure object
26 switch Used to define switch-case statement
27 typydef Used to define a temporary name for data type
28 union Used to combine different data type sharing the same
memory space

29 unsigned Used to modify a basic data type


30 void Means Nothing - pass as a parameter and return value
of a function

31 volatile Used to define a volatile variable object


32 while Used to define a while-loop statement
Operators in C
► The operators in C are the special symbols that we use for
performing various functions. Operands are those data items on
which we apply the operators. We apply the operators in between
various operands. On the basis of the total number of operands,
here is how we classify the operators:
► Unary Operator(-,+,*,&)
► Binary Operator
► Ternary Operator
► Unary Operator
The unary operator in c is a type of operator that gets applied to one single operand,
for example: (–) decrement operator, (++) increment operator, (type)*, sizeof, etc.
► Binary Operator
Binary operators are the types of operators that we apply between two of the
operands. Here is a list of all the binary operators that we have in the C language:
► Relational Operators
► Arithmetic Operators
► Logical Operators
► Shift Operators
► Conditional Operators
► Bitwise Operators
► Assignment Operator

► Ternary Operator
► Using this operator would require a total of three operands.ie conditional Operator ?:
in place of the if-else conditions.
Strings in C
► The strings in C always get represented in the form of an array of
characters. We have a ‘\0′ null character at the end of any string-
thus, this null character represents the end of that string.
► There are different ways in which we can describe a string:
► char x[9] = “chocolate’; // Here, the compiler allocates a total of 9 bytes to the ‘x’
array.
► char x[] = ‘chocolate’; // Here, the compiler performs allocation of memory during
the run time.
► char x[9] = {‘c’,’h’,’o’,’c’,’o’,’l’,’a’,’t’,’e’,’\0′}; // Here, we are representing the
string in the form of the individual characters that it has.
example
#include <stdio.h>
int main() {
char greetings[] = "Hello World!";
printf("%s", greetings);
return 0;
}

Output:
Hello World!
Special Characters in C
► The special characters in the C language, holds a special meaning that we cannot use for any
other purpose.
► () Simple brackets – Used this during function calling as well as during function declaration.
For instance, the function printf() is pre-defined.
► [ ] Square brackets – The closing and opening brackets represent the multidimensional and
single subscripts.
► (,) Comma – Used the comma for separating more than one statement, separating the function
parameters used in a function call, and for separating various variables when we print the value
of multiple variables using only one printf statement.
► { } Curly braces – Used it during the closing as well as opening of any code. We also use the
curly braces during the closing and opening of the loops.
► (*) Asterisk – Used for representing the pointers and we also use this symbol as a type of
operator for multiplication.
► (#) Hash/preprocessor – Used for the preprocessor directive. This processor basically denotes
that the user is utilizing the header file.
► (.) Period – Used for accessing a member of a union or a structure.
► (~) Tilde –Used in the form of a destructor for free memory.
Constant in C
► Constant is basically a value of a variable that does not change throughout a program.
► This will declare the variable as "constant“(const), which
means unchangeable and read-only:

► Example
► const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum‘
Comments in C
► Comments can be used to explain code, and to make it more readable. It can also be used
to prevent execution when testing alternative code.
► Comments can be singled-lined or multi-lined.
► Single-line comments start with two forward slashes (//).
► Any text between // and the end of the line is ignored by the compiler (will not be
executed). Normally used // for short comments
► Example
#include <stdio.h>
int main() {
// This is a comment
printf("Hello World!");
return 0;
}
▪ Multi-line Comments
► Multi-line comments start with /* and ends with */.
► Any text between /* and */ will be ignored by the compiler:
► Example:
#include <stdio.h>
int main() {
/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");
return 0;
}
Output function(printf statements).

► Syntax:

Form 1 : printf(“string”);

Form 2 : printf("format string",argument_list);

► The format string can be %d (integer), %c (character), %s (string), %f (float) etc.


User Input(scanf statements)
► To get user input, you can use the scanf() function:
► The scanf() function takes two arguments: the format specifier of the variable(myNum)
(%d in the example above) and the reference operator (&myNum), which stores the
memory address of the variable.
► The scanf() function also allow multiple inputs.
► We can get a string entered by the user.
► When working with strings in scanf(), you must specify the size of the string/array (we
used a very high number, 30 in our example, but atleast then we are certain it will store
enough characters for the first name), and you don't have to use the reference operator (&).
► scanf() function has some limitations: it considers space (whitespace, tabs, etc) as a
terminating character, which means that it can only display a single word (even if you type
many words).
► Syntax :
scanf(“control string”, arg1, arg2 , arg3 ,……., argn);
► Example:

#include <stdio.h>
int main() {
// Create an integer variable that will store the number we get from the user
int myNum;
// Ask the user to type a number
printf("Type a number and press enter: \n");
// Get and save the number the user types
scanf("%d", &myNum);
// Print the number the user typed
printf("Your number is: %d", myNum);
return 0;
}
Types Of Data Types In C
Data type Format Specifier

Long double %Lf

Octal integer %o

Short unsigned integer %u

Long decimal integer %ld

Hexadecimal integer %x

Print memory address in the %p


hexadecimal form

A string or sequence of character %s


► Escape Sequences:
Escape Purpose
Sequence
\b Backspace
\n New line
\t Tab
\v Vertical tab
\f New page\ Clear screen
\r Carriage return
► Standard Header Files :
❖ stdio.h : for standardized input and output functions.
❖ string.h : for string handling functions
❖ stdlib.h : for some miscellaneous functions
❖ conio.h : for clearing the screen
❖ alloc.h : for dynamic memory allocation
❖ math.h : for mathematical functions
Primary Data Types In C
► The C programming language has five primitive or primary data types.
► 1. Integer (int): Refers to positive and negative whole numbers (without decimal), such as
10, 12, 65, 3400, etc.
► Example
#include <stdio.h>
void main()
{
int i = 5;
printf("The integer value is: %d \n", i);
}
► 2. Character (char): Refers to all the character sets within single quotes such as ‘a’,
‘A’, etc.
► Example:
#include <stdio.h>
void main()
{
char c = 'b';
printf("The character value is: %c \n", c);
}
► 3. Floating-point (float): Refers to all the real number values or decimal points, such
as 3.14, 10.09, 5.34, etc.
► Example:
#include <stdio.h>
void main()
{
float f = 7.2357;
printf("The float value is: %f \n", f);
}
► 4. Double (double): Used when the range exceeds the numeric values that do
not come under either floating-point or integer data type.
► Example:
#include <stdio.h>
void main()
{
double d = 71.2357455;
printf("The double value is: %lf \n", d);
}
%c (Character) Format Specifier
#include <stdio.h>
int main()
{
char s;
printf("Enter the character: \n");
scanf("%c", &s);
printf("The character is: %c",s);
return 0;
}
Output: Enter the character
N
The character is:N
%s (String) Format Specifier
#include <stdio.h>
int main()
{
char s[25]=" I love C programming..! ";
printf("The string value of s is %s \n",s);
return 0;
}

Output: The string value of s is I love C programming..!


%lf (Double) Format Specifier
#include <stdio.h>
int main()
{
double d=12.5;
printf("The double value of d is %lf \n",d);
return 0;
}

Output: The double value of d is 12.500000


%o (octal integer) Format Specifier
#include <stdio.h>
int main()
{
int oct=11;
printf("The octal integer value of oct is %o \n",oct);
return 0;
}

Output: The octal interger value of oct is 13


%x (Hexadecimal Integer) Format Specifier
#include <stdio.h>
int main()
{
int h=14;
printf("The hexadecimal value of h is %x \n",h);
return 0;
}

Output:The hexadecimal value of h is e


%p (Prints Memory Address) Format Specifier
To find the memory address that holds values of a variable, we use the %p
format specifier, and it prints in hexadecimal form.

#include <stdio.h>
int main()
{
int sum=0;
printf("The memory address of sum is %p \n",&sum);
return 0;
}

► output: The memory address of sum is 000000000022FE4C


C Operators
► Operators are used to perform operations on variables and values.
Sample programs:
► To Adds together two values:
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x + y);
return 0;
}
Subtracts one value from another:
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x - y);
return 0;
}
► To Multiplies two values :
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x * y);
return 0;
}
To Divides one value by another:
#include <stdio.h>
int main() {
int x = 12;
int y = 3;
printf("%d", x / y);
return 0;
}
► To Returns the division remainder(Modulus):
#include <stdio.h>
int main() {
int x = 5;
int y = 2;
printf("%d", x % y);
return 0;
}
► Increases the value of a variable by 1(Increment)
#include <stdio.h>
int main() {
int x = 5;
printf("%d", ++x);
return 0;
}
► Decreases the value of a variable by 1(Decrement):

#include <stdio.h>
int main() {
int x = 5;
printf("%d", --x);
return 0;
}
► Write a Program to perform all arithmetic operations:
#include <stdio.h>
int main()
{
int x, y;
int sum, sub, mult, mod;
float div;
printf("Enter any two numbers: \n ");
scanf("%d%d", &x, &y);
sum = x+ y;
sub = x - y;
mult = x * y;
div = (float)x/ y;
mod = x % y;
printf("SUM = %d\n", sum);
printf("DIFFERENCE = %d\n", sub);
printf("PRODUCT = %d\n", mult);
printf("QUOTIENT = %f\n", div);
printf("MODULUS = %d", mod);
return 0;
}
► Write a program to subtract two long integers.
#include<stdio.h>
#include<conio.h>
int main()
{
long int num1, num2, diff=0;
printf("\n Enter the numbers:" );
scanf("%ld %ld", &num1, &num2);
diff= num1-num2;
printf("\n Difference = %ld", diff);
return 0;
}
Relational Operators in C
► The relational operators are used to perform the relational operation between two
operands or variables. e.g. comparison, equality check, etc.
► < If an expression is x < y, it will return TRUE if and only if x is
less than y, otherwise it will return FALSE.
► <= If an expression is x <= y, it will return TRUE if and only if x is
less than or equal to y, otherwise it will return FALSE.
► > If an expression is x > y, it will return TRUE if and only if x is
greater than y, otherwise it will return FALSE.
► >= If an expression is x >= y, it will return TRUE if and only if x is
greater than or equal to y, otherwise it will return FALSE.
► == If an expression is x == y, it will return TRUE if and only if x is
equal to y, otherwise it will return FALSE.
► != If an expression is x != y, it will return TRUE if and only if x is
not equal to y, otherwise it will return FALSE.
Bitwise Operators
► Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &,
|, and ^ are as follows:

Operator Description Example


Binary AND Operator
(A & B) = 12, i.e., 0000
& copies a bit to the result if
1100
it exists in both operands.
Binary OR Operator copies
(A | B) = 61, i.e., 0011
| a bit if it exists in either
1101
operand.
Binary XOR Operator
(A ^ B) = 49, i.e., 0011
^ copies the bit if it is set in
0001
one operand but not both.
Binary One's Complement
(~A ) = ~(60), i.e,. 1100
~ Operator is unary and has
0011
the effect of 'flipping' bits.
Operator Description Example

Binary Left Shift Operator.


The left operands value is
<< moved left by the number of A << 2 = 240 i.e., 1111 0000
bits specified by the right
operand.

Binary Right Shift Operator.


The left operands value is
>> moved right by the number A >> 2 = 15 i.e., 0000 1111
of bits specified by the right
operand.
Assignment Operators in C
► The following table lists the assignment operators supported by the C language.

Operator Description Example


Simple assignment operator.
Assigns values from right C = A + B will assign the
=
side operands to left side value of A + B to C
operand

Add AND assignment


operator. It adds the right
C += A is equivalent to C =
+= operand to the left operand
C+A
and assign the result to the
left operand.
Operator Description Example

Subtract AND assignment


operator. It subtracts the right
C -= A is equivalent to C = C
-= operand from the left
-A
operand and assigns the
result to the left operand.

Multiply AND assignment


operator. It multiplies the
C *= A is equivalent to C =
*= right operand with the left
C*A
operand and assigns the
result to the left operand.

Divide AND assignment


operator. It divides the left
C /= A is equivalent to C = C
/= operand with the right
/A
operand and assigns the
result to the left operand.
Operator Description Example

Modulus AND assignment


operator. It takes modulus
C %= A is equivalent to C =
%= using two operands and
C%A
assigns the result to the left
operand.

Left shift AND assignment C <<= 2 is same as C = C <<


<<=
operator. 2

Right shift AND assignment C >>= 2 is same as C = C >>


>>=
operator. 2

Bitwise AND assignment


&= C &= 2 is same as C = C & 2
operator.

Bitwise exclusive OR and


^= C ^= 2 is same as C = C ^ 2
assignment operator.

Bitwise inclusive OR and


|= C |= 2 is same as C = C | 2
assignment operator.
► Write a code which takes 10 and 3 as inputs and perform all the arithmetic
operators explained above, which should match expected output showed.
► Test Case 1:
► Expected Output:
Addition·Result·=·13
Subtraction·Result·=·7
Multiplication·Result·=·30
Division·Result·=·3
Remainder·=·1
► Increment and Decrement Operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}

You might also like