Fundamentals of C Programming and Data Representation
History and Development of C
The C programming language was evolved by Dennis Ritchie at Bell Laboratories.
It was originally implemented in 1972 on a DEC PDP-11 computer (Digital Equipment Corporation – Programmed Data Processor).
C first gained widespread recognition as the development language for the UNIX operating system.
In the modern era, nearly all major operating systems are developed using C, C++, or a combination of both.
C is highly versatile and is available for the vast majority of computer systems.
The language is considered mostly hardware independent.
C Character Set
A character set is the collection of valid characters that a specific language is capable of recognizing.
The C character set is categorized into four main groups:
Letters: Lowercase 'a' through 'z' and uppercase 'A' through 'Z'.
Digits: through .
Special Characters: Examples include , , , , &, , , , and .
White Spaces: Including New line (), Tab (), and Vertical Tab ().
C Keywords
Keywords are reserved words within the C language that hold predefined meanings for the compiler.
These words cannot be utilized as names for variables or constants.
The meanings of keywords are fixed and cannot be altered by the programmer.
There are 32 standard compiler-specific keywords:
auto,double,int,structbreak,else,long,switchcase,enum,register,typedefchar,extern,return,unionconst,float,short,unsignedcontinue,for,signed,voiddefault,goto,sizeof,volatiledo,if,static,while
C Tokens
A token is defined as a group of characters that logically belong together.
Programs are constructed by the programmer using various types of tokens.
The primary categories of C tokens include:
Keywords: e.g.,
break,int,float.Identifiers: Used for variable names, constant names, function names, and array names.
Operators: e.g., , , \text{%}.
Strings: e.g.,
"hello","123","s".Constants: e.g., , ,
'A','g',"hello".Special Symbols: e.g., , , , &, .
Structure of a C Program
A standard C program follows a specific hierarchical structure:
Preprocessor Directives: Used to include header files (e.g.,
#include <stdio.h>).Main Function: Defined as
void main()orint main(), representing the entry point of execution.Delimiters: The body of the program must be enclosed within curly braces
{ }.Program Body: Contains variable declarations and executable statements.
Statement Termination: Every statement in C must end with a semicolon (
;).
Header Files and Preprocessor Directives
#include <stdio.h>: Standard Input Output header, required for functions likeprintf()andscanf().#include <conio.h>: Console Input Output header, often used for functions likeclrscr()to clear the screen.
Essential Format Specifiers
Format specifiers are used to dictate the type of data being handled during input and output operations:
%c: Character (signed or unsigned).%d: Signed integer (holds both positive and negative values).%u: Unsigned integer (holds only positive values).%h: Short integer.%hu: Unsigned short integer.%ld: Long signed integer.%lu: Long unsigned integer.%f: Decimal floating-point values (prints 6 decimal places by default).%lf: Double-precision floating-point values.%Lf: Long double-precision floating-point values.%eor%E: Scientific notation (Mantissa/Exponent).%s: Strings (sequences of characters).
Symbolic Names for Control Characters (Escape Sequences)
These symbolic names represent specific ASCII control characters used for formatting output:
\0: Null character\a: Alert (bell)\b: Backspace\t: Horizontal tab\n: Newline\v: Vertical tab\f: Form feed\r: Carriage return\': Single quote\": Double quote\\: Backslash
Variables in C
Definition: A variable is a container or storage area in the computer's memory used to hold data.
Identifiers: Each variable requires a unique name to identify its storage location.
Usage: Variables must be declared before they can be used in a program.
Nature: A variable's value can change multiple times during program execution.
Rules for Valid Variable Names (Identifiers)
Must begin with a letter or an underscore (
_).The first character can be followed by any combination of letters, underscores, or digits.
Keywords are strictly prohibited as variable names.
C is case-sensitive:
sum,Sum, andSUMare treated as three distinct variables.While variable names can be of any length, typically only the first 31 or 63 characters are significant.
Advantages of Declaring Variables
Centralization: Listing all variables at the beginning makes the program easier to understand.
Planning: It forces the programmer to plan the program logic before writing code.
Bug Prevention: Mandatory declaration helps prevent errors caused by misspelled variable names.
Memory Management: It allows the compiler to determine the exact amount of memory needed.
Type Verification: It enables the compiler to verify that operations performed on a variable are compatible with its data type.
Input and Output Functions
Output: printf()
Defined in
stdio.h.Used to display data on the monitor.
Example:
printf("%d", number);prints the integer value of the variablenumber.
Input: scanf()
Defined in
stdio.h.Used to obtain values from the user via the keyboard.
The address-of operator (
&) is used to store the input into the memory location of the variable.Example:
scanf("%d", &num);reads an integer and stores it in variablenum.
Syntax vs. Logical Errors
Syntax Errors: Violations of the programming language's grammatical rules. These are detected by the compiler (e.g., missing a semicolon at the end of a
printfstatement).Logical (Semantic) Errors: The program is syntactically correct and runs, but the output is incorrect because the underlying meaning or logic is flawed.
Constants and Literals
Constants are data values that remain unchanged throughout the execution of a program. Like variables, they possess a data type.
Literals: These are fixed values assigned to constant variables. For example, in
const int a = 10;,is an integer literal.
Types of Constants
Decimal Constant: e.g., , , .
Real/Floating-Point Constant: e.g., , , .
Octal Constant: Must start with a 0; e.g., , , .
Hexadecimal Constant: Must start with 0x; e.g., , , .
Character Constant: Enclosed in single quotes; e.g.,
'a','b'.String Constant: Enclosed in double quotes; e.g.,
"c program".
Defining Constants
There are two primary methods to define constants in C:
The
constkeyword: e.g.,const int a = 10;.The
#definepreprocessor directive: e.g.,#define PI 3.14159.
Data Types in C
C data types are categorized into several groups:
Basic:
int,char,float,double.Derived: Arrays, pointers, etc.
Enumeration:
enum.Void:
void.
Integer and Character Types
Standard Signed types:
int,short int,long int,signed char.Standard Unsigned types:
unsigned int,unsigned short int,unsigned long int,unsigned char.
Floating-Point Types
These represent real numbers and consist of an integer part and a fractional part.
Example: In the number , the integer part is and the fractional part is .
Scientific Notation: Expressed as a mantissa and an exponent. Example: represents .
The Void Type
void has two primary uses in C:
To specify the return type of a function that returns no value.
To indicate that a function has an empty argument list.
Programming Best Practices: Variable Naming Standards
A common standard involves using prefixes to identify the data type of a variable:
i:intorunsigned int(e.g.,iTotalMarks)f:float(e.g.,fAverageMarks)d:double(e.g.,dSalary)l:longorunsigned long(e.g.,lFactorial)c:signed charorunsigned char(e.g.,cChoice)ai: Array of integers (e.g.,aiStudentId)af: Array of floats (e.g.,afQuantity)ad: Array of doubles (e.g.,adAmount)al: Array of long integers (e.g.,alSample)ac: Array of characters (e.g.,acEmpName)
Enumerations (enum)
Enumeration or
enumis a user-defined data type in C used to assign names to integral constants.It improves program readability and maintainability.
Declaration and Initialization
Example:
enum week{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};.Every element in an enum has an initial predefined value starting from by default.
Values can be manually initialized:
enum status_codes { OKAY = 1, CANCEL = 0, ALERT = 2 };.
Critical Facts Regarding Enums
Multiple names can share the same value (e.g.,
enum point {x = 0, y = 0, z = 0};will output ).Values can be assigned in any order. Any unassigned name will automatically take the value of the preceding name plus (e.g.,
enum point {y = 2, x = 34, t, z = 0};results in , , , and ).Only integral values are permitted. Attempting to assign a floating-point value (e.g.,
y = 2.5) will result in a compiler error stating the value is not an integer constant.Enum constants must be unique within their scope. Redeclaring the same constant name in multiple enums (e.g., using
xin bothpoint1andpoint2) will cause a compilation error.
Practical Examples
Swapping Two Numbers without a Temporary Variable
#include<stdio.h>
main() {
int a = 5, b = 6;
a = a + b; // a becomes 11
b = a - b; // b becomes 5
a = a - b; // a becomes 6
printf("Final a=%d and b=%d", a, b);
}
Calculating the Area of a Rectangle
#include <stdio.h>
int main() {
int length, breadth, area;
printf("Enter length\n");
scanf("%d", &length);
printf("Enter breadth\n");
scanf("%d", &breadth);
area = length * breadth;
printf("Area is %d\n", area);
return 0;
}