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

Introduction To C

notes of c

Uploaded by

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

Introduction To C

notes of c

Uploaded by

tatova7977
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

General Aspect of ‘C’

C was originally developed in the 1970s, by Dennis Ritchie at Bell Telephone


Laboratories, Inc.
C is a High level, general –purpose structured programming language.
Instructions of C consists of terms that are very closely same to algebraic
expressions, consisting of certain English keywords such as if, else, for ,do
and while
Steps in learning NATURAL LANGUAGE

Steps in learning ‘C’LANGUAGE


Basic structure of C Program
The C Character Set: The character set in C is a collection of characters that
the language recognizes and can use to form words, expressions, and
numbers in a source program.
Special Characters
Backlash character constants (or) Escape sequence in C programming:
C Tokens: The individual words and punctuation marks are called tokens.
In a C program, the smallest individual units are knows as C tokens.
Keywords: Keywords are nothing but system
defined identifiers.
• Keywords are auto Double int struct
reserved words of
the language
break Else long switch
• They have specific
meaning in the
case Enum register typedef
language and
cannot be used by
the programmer as char Extern return union
variable or
constant names const float short unsigned
• C is case senitive, it
means these must continue for signed void
be used as it is
• 32 Keywords in C default goto sizeof volatile
Programming
do if static while
Variables:
A variable is a data name that may be used to store a data value.
Unlike constant that remain unchanged during the execution of a
program, a variable may be taken different values at different times
during execution
Rules for Naming a Variable in C
We give a variable a meaningful name when we create it. Here are
the rules that we must follow when naming it:
1. The name of the variable must not begin with a digit. They must
begin with a letter.
2. A variable name can consist of digits, alphabets, and even special
symbols such as an underscore ( _ ).
3. A variable name must not have any keywords, for instance, float,
int, etc.
4. There must be no spaces or blanks in the variable name.
5. The C language treats lowercase and uppercase very differently,
as it is case sensitive. Usually, we keep the name of the variable in
the lower case.
Identifiers: refer to the names of variables, functions and arrays.
Constants: The constants in C are the read-only variables whose values
cannot be modified once they are declared in the C program.
Data Types: Each variable in C has an associated data type. It specifies the
type of data that the variable can store like integer, character, floating,
double, etc. Each data type requires different amounts of memory and has
some specific operations which can be performed over it.
Integer (int): This is a fundamental type that stores whole numbers, such as 5, 67, and
2390
Character: This type stores single characters and ASCII character sets, such as 'x‘, 'Y'.
Double: This type stores large numeric values that are not integers or floating-point
numbers. It can store twice as much data as a float.
Floating-point: This type stores decimal and exponential values, such as 40.1,
820.673, and 5.9.
Void: This type indicates that there are no values. It's often used when defining
functions in a program
Calculate range of Data Types: 1. Convert the bytes into bits.
2. For signed data types, use formula -2(n-1) to (2(n-1)) – 1.
3. For unsigned data types, use formula 0 to (2n) – 1. Where n is the number of bits in
:
both the cases. 32 bits
Conversion of High level language to Low level language

Binary Number System


Programming: involves creating a set of instructions that a
computer can follow to perform specific tasks or solve problems.
Programming is the process of designing, writing, testing, debugging,
and maintaining the source code of computer programs.
Algorithm: An algorithm in C is a step-by-step procedure for solving a
problem or performing a task, implemented using the C programming
language. It's a set of instructions that takes some input, processes it,
and produces an output.
2 types:
Pseudocode is a way to represent the logic of a program using plain
language, without adhering to the strict syntax of a specific
programming language.
Flowcharts normally use standard symbols to represent the different
types of instructions. These symbols are used to construct the flowchart
and show the step-by-step solution to the problem.
Operators: An operator is a symbol that operates on a value or a variable.
C language offers a wide variety of operators to perform different operations.
1.Arithmetic Operators 2. Relational Operators
3. Logical Operators 4. Assignment Operators
5. Increment/Decrement Operators 6. Conditional (Ternary) Operator
7. Bitwise Operators 8. Miscellaneous Operators
Arithmetic Operators
An arithmetic operator in C is a symbol used in the language that represents a
specific mathematical operation between two operands. These operators
include addition (+), subtraction (-), multiplication (*), division (/), and
modulus (%).
Real Arithmetic: The arithmetic operations involving only real operands is
called real arithmetic. The modulo division operator %f cannot be used on
floating point data
2. Relational Operators
Relational operators in C are used to compare two values. These operators
return either true (non-zero) or false (zero), depending on whether the
relationship between the values holds true.

3. Logical Operators
The logical operators evaluate the logical expression and return a result. The
result is always a Boolean value. A Boolean value determines whether the
expression is true or false. There are three logical operators in C
programming: logical AND( && ), logical OR( || ), and logical NOT ( ! ).
1. Logical AND (&&):This operator returns true if both operands are true;
otherwise, it returns false.
2. Logical OR (||): This operator returns true if at least one of the operands is
true; if both are false, it returns false.
3. Logical NOT (!): This operator negates the truth value of the operand. It
returns true if the operand is false, and vice versa
4. Assignment Operators
Assignment operators are used to assign values to variables. The most basic
assignment operator is the = operator, but there are several compound
assignment operators that combine other operations (like addition, subtraction)
with assignment.
5. Increment/Decrement Operators: are used to increase or decrease the value of a
variable by 1. There are two types of increment and decrement operators:
Increment Operator (++): The increment operator increases the value of a variable by
1
Prefix Increment (++a): Increases the value of a before it is used in the expression.
Example: int a = 5;
int b = ++a; // a is first incremented to 6, then b is assigned the value 6
Postfix Increment (a++): Uses the current value of a in the expression and then
increments a.
Example: int a = 5;
int b = a++; // b is assigned the value 5, then a is incremented to 6
Decrement Operator (--): decreases the value of a variable by 1.
Prefix Decrement (--a): Decreases the value of a before it is used in the expression.
Example: int a = 5;
int b = --a; // a is first decremented to 4, then b is assigned the value 4
Postfix Decrement (a--): Uses the current value of a in the expression and then
decrements a.
Example: int a = 5;
int b = a--; // b is assigned the value 5, then a is decremented to 4
6. Conditional (Ternary) Operator: is a shorthand way of writing simple if-else
statements. It takes three operands and is used to evaluate a condition, returning one
value if the condition is true and another value if the condition is false. The syntax of
the ternary operator is:
condition ? value_if_true : value_if_false;
Syntax Explanation:
condition: An expression that evaluates to either true (non-zero) or false (zero).
value_if_true: The value that is returned if the condition is true.
value_if_false: The value that is returned if the condition is false.
7. Bitwise Operators: used to perform operations at the bit
level. These operators manipulate individual bits of integer
values (like int, char, etc.), allowing for efficient low-level
data processing.
Example: Bitwise AND (&)
a = 5; // Binary: 0101
b = 3; // Binary: 0011
result = a & b; // Binary: 0001, result = 1

8. Miscellaneous Operators:
Precedence of arithmetic operations (the order of operations) dictates the
sequence in which operations are performed in an arithmetic expression.
The standard order is:
1.Parentheses (): Operations inside parentheses are performed first.
2.Exponents ^: Exponential calculations come next (e.g., 23=8).
3.Multiplication *, Division / and modulus %: These operations are performed
from left to right. They are of equal precedence, so you evaluate them as they appear
in the expression, moving left to right.
4. Addition + and Subtraction -: Also performed from left to right, with equal
precedence, evaluated in the order they appear.
5. If parentheses are nested, the evaluation begins with the innermost sub-expression
For the expression: 3+6×(5+4)2÷3−2 Final result: 163.
Type conversion (or type casting) refers to converting a variable from one data type
to another, either automatically or explicitly, in the context of an expression.
There are two types of type conversions in C:
Implicit Conversion (Type Promotion): The compiler automatically converts a
variable from one type to another when required by the expression. For example,
when performing an operation between an int and a float, the int is automatically
promoted to float to avoid losing precision.
Rules for implicit conversion:
1. Integer types smaller than int (like char or short) are promoted to int.
2. If one operand is double and the other is float, the float is promoted to double.
3. If one operand is long and the other is int, the int is promoted to long.
Explicit Conversion (Type Casting): The programmer can force a conversion by
specifying the desired type. This is known as explicit type casting.
The syntax is: (type) expression
Arithmetic Type Conversion in Expressions:
Usual arithmetic conversions: After promotions, if one operand is float and the other is
int, the int is converted to float. If one is double, the other is converted to double.

Program
#include <stdio.h>
int main() {
int a = 5;
float b = 4.5;
// Implicit conversion: 'a' is promoted to float before addition
float result1 = a + b;
printf("Result1: %.2f\n", result1); // Outputs: 9.50
// Explicit conversion: 'a' is cast to float
float result2 = (float) a / 2;
printf("Result2: %.2f\n", result2); // Outputs: 2.50
return 0;
}
Implicit Type Conversion
Mathematical Functions: are available through the standard math library math.h. To
compile a C program using math functions, you must link the math library explicitly.
Here are some common mathematical functions in C:
Basic Arithmetic Functions Trigonometric Functions
double pow(double base, double double sin(double x);
exponent); Returns the sine of `x` (in radians).
Example: pow(2, 3) returns 8.0 Example: sin(3.14159 / 2) returns 1.0.
double sqrt(double x); double cos(double x);
Example: sqrt(16) returns 4.0 Returns the cosine of `x` (in radians).
double fabs(double x); Example: cos(0) returns 1.0.
Returns the absolute value of `x`. double tan(double x);
Example: fabs(-5.5)` returns 5.5. Returns the tangent of `x` (in radians).
Logarithmic and Exponential Functions Example: tan(3.14159 / 4) returns 1.0.
double log(double x); double asin(double x);
Returns the natural logarithm (base `e`) of
Returns the arcsine of `x` (in radians).
`x`. Example: log(2.71828) returns 1.0.
double acos(double x);
double log10(double x);
Returns the base-10 logarithm of `x`.
Returns the arccosine of `x` (in
Example: log10(100) returns 2.0. radians).
double exp(double x); double atan(double x);
Returns `e` raised to the power of `x`. Returns the arctangent of `x` (in
Example: exp(1) returns 2.71828. radians).
4. Rounding and Remainder Functions
double ceil(double x); Returns the smallest integer greater than or equal to `x`.
Example: ceil(3.7) returns 4.0.
double floor(double x); Returns the largest integer less than or equal to `x`.
Example: floor(3.7) returns 3.0.
double fmod(double x, double y);
Returns the remainder of `x` divided by `y` (i.e., x % y).
Example: fmod(10.5, 3) returns 1.5.
Example Usage
#include <stdio.h>
#include <math.h>
int main() {
double x = 9.0;
double result = sqrt(x); // Calculates square root of 9.0
printf("Square root of %.2f is %.2f\n", x, result);
double y = 2.0;
double power = pow(y, 3); // Calculates 2^3
printf("%.2f raised to the power of 3 is %.2f\n", y, power);
return 0;
}
Managing Input and Output Operations
Reading a character:
scanf() is a formatted input getchar() fgetc(stdin)
function variable_name = gatchar(); variable_name =
fgetc(stdin);
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() { int main() { int main() {
char ch; char ch; char ch;
printf("Enter a character: printf("Enter a character: "); printf("Enter a character:
"); ch = getchar(); // Reads a ");
scanf("%c", &ch); single character ch = fgetc(stdin);
printf("You entered: %c\ printf("You entered: %c\n", printf("You entered: %c\n",
n", ch); ch); ch);
return 0; return 0; return 0;
} } }
The scanf() function is a commonly used input function. It allows you to read input
from the user or from a file and store that input in variables of different data types.
Syntax of scanf:
scanf(“control string”,arg1,arg2,…,argn);
The control string specifies the field format in which the data is to be entered and
arguments specifies the address of location where the data is stored. control string and
arguments are separated by comma.
Formatted input: refers to reading input in a specific format from the user or a file
using functions like scanf() or fscanf(). These functions allow you to specify the
data type and format in which the input should be interpreted, using format
specifiers. scanf() Function is reads data according to the format string and stores it
in the provided variables. %d : Reads an integer (int)
%f : Reads a floating-point number (float)
%lf: Reads a double
%c : Reads a single character
%s : Reads a string (character array)
%x : Reads a hexadecimal integer
%o : Reads an octal integer
%ld: Reads a long signed intger
%d or %i Reads a short signed intger
%lu : Reads a long unsigned int
%u reads a short unsigned ; L for long double
Not working:%u : unsigned integer and %e exponent
Inputting Numbers:
The filed specification to read a integer number is : % w d
The percentage sign indicates that a conversion specification follows. w is an integer
number that specifies the width of the number to be read and d, known as data type
character , indicates that the number to be read in integer mode
Scanf(“%2d %5d”, &num1, &num2);
Reading Multiple Values
#include <stdio.h>
int main() {
int num1; float num2; char ch;
printf("Enter an integer, a float, and a character: ");
scanf("%d %f %c", &num1, &num2, &ch); // Reading multiple inputs
printf("Integer: %d\nFloat: %.2f\nCharacter: %c\n", num1, num2, ch);
return 0;
}
Important Considerations with scanf()
1. Whitespace Handling: scanf() skips leading whitespace (spaces, tabs, newlines) for
most format specifiers (like %d, %f, %s), but not for %c. To avoid this issue with %c,
you can add a space before %c in the format string (e.g., " %c").
2. Buffer Overflow: When reading strings with %s, be cautious of buffer overflows.
To limit the number of characters is to be read by specifying a maximum width
scanf("%19s", str); // Limits input to 19 characters, ensuring the string doesn't
overflow
3. Return Value: scanf() returns the number of items successfully read. You can use
this return value to check if the input was successfully parsed.

Reading Input with Spaces in Strings


scanf("%[^\n]%*c", str); // %[^\n] reads until newline
Formatted Output:
printf: the printf() function is used to format and display output. It allows to specify how
values should be printed, using format specifiers.
printf(“control string”,arg1,arg2,…,argn);
Control string consists of three types of items:
1.Character that will be printed on the screen as they appear.
2.Format specifications that define the output format for display of each item.
3.Escape sequence characters such as \n, \t, and \b.
The arguments are the variables whose values are formatted and printed according to the
specifications of the control string
A simple format specification has the following form
%w.p type-specifier
Where w is an integer number that specifies the total number of column fot the output value
and p is another integer number that specifies the number of digits to the right of the decimal
point. printf never specifies a new line automatically
Out put of integer numbers: %wd
Printing of stringd: %w.ps
#include <stdio.h>
int main() {
int num1 = 5, num2 = 12345;
float num = 4573.14159; // Output
printf("Right-aligned integers:\n");
printf("%5d\n", num1); // 5 spaces width, right-aligned 5
printf("%5d\n", num2); // 5 spaces width, right-aligned 12345
printf("%-5d\n", num1); // 5 spaces width, left-aligned 5
printf("%5d\n", -num1); // right-aligned negative value -5
printf("%f\n", num); // 4573.141602
printf(" %.2f\n", num);// Only two decimal places 4573.14
printf(" %7.4f\n", num); // 4573.1416
printf("%e\n",num); // 4.573142e+03
printf("%-10.2e\n",num); // 4.57e+03
printf("%10.2e\n",-num); // -4.57e+03
return 0;
}
Exercise
1. Convert the following equations into corresponding C statements.

2. The distance between two cities (in km.) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimetres.

3. The length & breadth of a rectangle and radius of a circle are input through the
keyboard. Write a program to calculate the area & perimeter of the rectangle, and the
area & circumference of the circle.

4. If a five-digit number is input through the keyboard, write a program to calculate


the sum of its digits.

5. If the marks obtained by a student in five different subjects are input through the
keyboard, find out the aggregate marks and percentage marks obtained by the student.
Assume that the maximum marks that can be obtained by a student in each subject is
100.

6. If a four-digit number is input through the keyboard, write a program to obtain the
sum of the first and last digit of thisnumber.

You might also like