Chapter-01(C Programming Fundamentals)
Chapter-01(C Programming Fundamentals)
Background
Computer Science: A
Structured Programming 1
Approach Using C
C Programs
Computer Science: A
Structured Programming 2
Approach Using C
FIGURE 2-2 Structure of a C Program
Computer Science: A
Structured Programming 3
Approach Using C
FIGURE 2-3 The Greeting Program
Computer Science: A
Structured Programming 4
Approach Using C
Documentation Section
•The Documentation Section consists of set of comment lines giving the
The author
Syntax
Example
/* c –program to find gcd and lcm of two numbers using Euclid's Algorithm *\
// Welcome to C
Link Section
•The link section provides instruction to the complier to
link functions from system library
•Syntax
#include<header file name .h>
Header files
stdio– Standard Input /Output
conio– Console input/Output,
math- contains mathematical functions like(cos(),
sin(), sqrt(), abs())
•Example
#include<stdio.h>
#include<conio.h>
Definition Section
•This section is used to define symbolic constants
•Syntax:-
•Example:-
#define pi 3.142
#define minmarks 35
Global declaration Section
Computer Science: A
Structured Programming 11
Approach Using C
Table 2-1 Rules for Identifiers
Computer Science: A
Structured Programming 12
Approach Using C
Note
An identifier must start with a letter or underscore:
it may not have a space or a hyphen.
Computer Science: A
Structured Programming 13
Approach Using C
Note
C is a case-sensitive language.
Computer Science: A
Structured Programming 14
Approach Using C
Table 2-2 Examples of Valid and Invalid Names
Computer Science: A
Structured Programming 15
Approach Using C
Variable declaration
•Syntax:-
data-type variable-name;
Ex:-
int a,x;
float b,c;
char name;
Data types in C
Example: 0, -5, 10
For example:
int id;
Here, id is a variable of type integer.
Similarly, int of 2 bytes, it can take 216 distinct states from -215 to
215-1. If you try to store larger number than 231-1,
i.e,+2147483647 and smaller number than -231, i.e, -2147483648,
program will not run correctly.
Floating types
Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0
etc.
For example:
float accountBalance; double bookPrice;
Here, both accountBalance and bookPrice are floating type variables.
The size of float (single precision float data type) is 4 bytes. And the
size of double (double precision float data type) is 8 bytes. Floating
point variables has a precision of 6 digits whereas the precision of
double is 14 digits.
Character types
Qualifiers alters the meaning of base data types to yield a new data
type.
Size qualifiers
Size qualifiers alters the size of a basic type. There are two size
qualifiers, long and short. For example:
long double i;
There is another qualifier signed which can hold both negative and
positive only. However, it is not necessary to define
variable signed since a variable is signed by default.
An integer variable of 4 bytes can hold data from -2 ^31 to 2^31-1.
However, if the variable is defined as unsigned, it can hold data from
0 to 2^32-1.
It is important to note that, sign qualifiers can be applied to int and
char types only.
C Programming
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits
0123456789
Special Characters
Special Characters in C Programming
, < > . _
, < > . _
( ) ; $ :
( ) ; $ :
% [ ] # ?
' & { } "
%
^ ! * /[ | ] # ?
- \ ~ +
^ ! * / |
- \ ~ +
For example:
int money;
Keywords in C Language
Identifiers are the names you can give to entities such as variables,
functions, structures etc.
For example:
Computer Science: A
Structured Programming 9
Approach Using C
Here ,you will learn about identifiers and proper way to name
an identifier.
Computer Science: A
Structured Programming 10
Approach Using C
Note
An identifier must start with a letter or underscore:
it may not have a space or a hyphen.
Computer Science: A
Structured Programming 11
Approach Using C
Note
C is a case-sensitive language.
Computer Science: A
Structured Programming 12
Approach Using C
Table 2-2 Examples of Valid and Invalid Names
Computer Science: A
Structured Programming 13
Approach Using C
Rules for writing an identifier
A valid identifier can have letters (both uppercase and lowercase letters), digits
and underscore only.
You can choose any name for an identifier. However, if the programmer choose meaningful name
for an identifier, it will be easy to understand and work on.
Variables
Variable is a name of data to store its value.
In programming, a variable is a container (storage area) to hold data.
Variable declaration
•Syntax:-
data-type variable-name;
Ex:-
int a,x;
float b,c;
char name;
Note
When a variable is defined, it is not initialized.
We must initialize any variable requiring
prescribed data when the function starts.
To indicate the storage area, each variable should be given a unique name
(identifier).
Variable names are just the symbolic representation of a memory location.
Sintax:
Data_type Data_name;
For example:
int playerScore = 95;
In C programming, you have to declare a variable before you can use it.
2.4 Memory Concepts
• Variables
– Variable names correspond to locations in the
computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable
(through scanf, for example), it replaces (and
destroys) the previous value
– Reading variables from memory does not change
them
• A visual representation
integer1 45
5
What is a Variable? symbol table?
A variable name can have letters (both uppercase and lowercase letters), digits
and underscore only.
There is no rule on how long a variable can be. However, the first 31 characters of
a variable are discriminated by the compiler. So, the first 31 letters of two variables
in a program should be different.
Constants
For example:
-2.0 0.0000234 -0.22E-5
Note: E-5 = 10-5
Character constants
A character constant is a constant which uses single quotation around
characters.
String constants are the constants which are enclosed in a pair of double-quote
marks.
For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n“ //prints string with newline
Enumeration constants
For example:
Here, color is a variable and yellow, green, black and white are the enumeration
constants having value 0, 1, 2 and 3 respectively. For more information, visit
page: C Enumeration.
C Programming Input Output (I/O): printf() and scanf()
Two commonly used functions for I/O (Input/Output) are printf() and
scanf().
Output
C Programming
How this program works?
All valid C program must contain the main() function.
The code execution begins from the start of main() function.
The printf() is a library function to send formatted output to the
screen.
The printf() function is declared in "stdio.h" header file.
Welcome to C!
• Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
• #include <stdio.h>
– Preprocessor directive
• Tells computer to load contents of a certain file
5 – <stdio.h> allows standard input/output operations
Example #2: C Integer Output
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
Output
Enter an integer: 4 Number = 4
The scanf() function reads formatted input from the keyboard. When
user enters an integer, it is stored in variable testInteger. Note
the '&'sign before testInteger; &testInteger gets the address
of testInteger and the value is stored in that address.
Example #3: C Floats Input/Output
#include <stdio.h>
int main()
{
float f;
printf("Enter a number: ");
// %f format string is used in case of floats
scanf("%f",&f);
printf("Value = %f", f);
return 0;
}
Output
Enter a number: 23.45 Value = 23.450000
The format string "%f" is used to read and display formatted in case of
floats.
Example #4: C Character I/O
#include <stdio.h>
int main()
{
char var1;
printf("Enter a character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
return 0;
}
Output
Enter a character: g You entered g.
• = (assignment operator)
– Assigns a value to a variable
– Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
– Variable receiving value on left
• printf( "Sum is %d\n", sum );
– Similar to scanf
• %d means decimal integer will be printed
• sum specifies what integer will be printed
– Calculations can be performed inside printf
statements
printf( "Sum is %d\n", integer1 +
integer2 );
11
Little bit on ASCII code
When a character is entered in the above program, the character itself is not
stored. Instead a numeric value(ASCII value) is stored. And when we displayed that
value using "%c" text format, the entered character is displayed.
#include <stdio.h>
int main()
{ int var1 = 69;
printf("Character having ASCII value 69 is %c.",var1);
return 0;
}
Output
Character having ASCII value 69 is E.
Example #5: C ASCII Code
#include <stdio.h>
int main()
{ char var1;
printf("Enter a character: ");
scanf("%c",&var1); // When %c text format is used, character is
displayed in case of character types
printf("You entered %c.\n",var1); // When %d text format is used,
integer is displayed in case of character types
printf("ASCII value of %c is %d.", var1, var1);
return 0;
}
Output
Enter a character: g You entered g. ASCII value of g is 103. The ASCII
value of character 'g' is 103. When, 'g' is entered, 103
Example #7: I/O of Floats and Integers
#include <stdio.h>
int main()
{ int integer = 9876;
float decimal = 987.6543; // Prints the number right justified within 6 columns
printf("4 digit integer right justified to 6 column: %6d\n", integer);
// Tries to print number right justified to 3 digits but the number is not right adjusted
because there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
// Rounds to two digit places
printf("Floating point number rounded to 2 digits: %.2f\n",decimal);
// Rounds to 0 digit places
printf("Floating point number rounded to 0 digits: %.f\n",987.6543);
// Prints the number in exponential notation(scientific notation)
printf("Floating point number in exponential form: %e\n",987.6543);
return 0;
}
Output
* multiplication
/ division
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Example #3: Assignment Operators
// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c; Output
c = a;
printf("c = %d \n", c);
c=5
c += a; // c = c+a
printf("c = %d \n", c); c = 10
c -= a; // c = c-a c=5
printf("c = %d \n", c); c = 25
c *= a; // c = c*a c=5
printf("c = %d \n", c);
c=0
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
C Relational Operators
== Equal to 5 == 3 returns 0
12
// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main() Output
{
int a = 5, b = 5, c = 10; 5 == 5 = 1
printf("%d == %d = %d \n", a, b, a == b); // true 5 == 10 = 0
printf("%d == %d = %d \n", a, c, a == c); // false 5>5=0
printf("%d > %d = %d \n", a, b, a > b); //false 5 > 10 = 0
printf("%d > %d = %d \n", a, c, a > c); //false 5<5=0
printf("%d < %d = %d \n", a, b, a < b); //false 5 < 10 = 1
printf("%d < %d = %d \n", a, c, a < c); //true 5 != 5 = 0
printf("%d != %d = %d \n", a, b, a != b); //false 5 != 10 = 1
printf("%d != %d = %d \n", a, c, a != c); //true 5 >= 5 = 1
printf("%d >= %d = %d \n", a, b, a >= b); //true 5 >= 10 = 0
printf("%d >= %d = %d \n", a, c, a >= c); //false 5 <= 5 = 1
printf("%d <= %d = %d \n", a, b, a <= b); //true 5 <= 10 = 1
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;
}
Oper
Meaning of Operator Example
ator
Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)
&&
operands are true && (d > 5))equals to 0.
Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5)
||
one operand is true || (d > 5))equals to 1.
Logical NOT. True only if the If c = 5 then, expression ! (c == 5) equals to
!
operand is 0 0.
Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
15
Arithmetic
• Arithmetic operators:
C o p era tio n Arithm etic Alg eb ra ic C exp ressio n
o p era to r exp ressio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
• Rules Operation(s)
Operator(s)of operator precedence:
Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
*, /, or % Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
16
Expressions and Evaluation
Expressions combine Values using Operators, according to precedence.
1 + 2 * 2 1 + 4 5
(1 + 2) * 2 3 * 2 6
Don’t confuse = and ==! The compiler will warn “suggest parens”.
19