Introduction to Programming in C
Introduction to Programming in C
C has become one of the most widely used programming languages due to its
efficiency, flexibility, and portability.
C was developed to implement the UNIX operating system, which is written in
C. It quickly gained popularity due to its ability to produce efficient programs
and its portability across different computer platforms.
C has influenced many other programming languages, including C++, Java,
and Python, making it an essential language for understanding computer science
concepts.
Characteristics of the C Language(1)
Procedural: C follows a procedural programming paradigm, where programs are
composed of procedures or functions that perform specific tasks.
Portable: C programs can be compiled and run on different platforms with minimal
changes, thanks to its low-level features and standard libraries.
Fast: C programs are typically fast and efficient due to their close relationship
with the underlying hardware.
Structure of a C Program(1)
• Preprocessor directives – Statements that
Preprocessor Directives begin with the # symbol. They are used for
including header files, defining constants and
Global Declarations other preprocessing tasks
• Global declarations – declarations of global
Function Definitions variables
int main () { • Function declarations/definitions- used to
introduce functions to the compiler
Local Declarations
• Main Function: Every C program must have
a main() function, which serves as the entry
Statements
point for the program. Execution of the
program begins from main function.
}
Structure of a C Program(2)
int main () {
int y; Local Declaration
Function printf("Enter x and y: ");
scanf(&x,&y); Statements
printf("Sum is %d\n",x+y);
}
Structure of a C Program(3)
Preprocessor Directives
• Begin with #
• Instruct compiler to perform some transformation to
file before compiling
• The line of code #include <stdio.h> adds the
header file stdio.h to this file
– .h is an extension for header file
– stdio.h is a header file that defines useful input/output
functions like printf() and scanf()
Global and Local Declarations
• Global and Local Declarations refer to where variables are defined and their
scope within the program
• Global Variables
– Are declared outside of any function and typically at the beginning of the
program
– Are visible throughout program(have global scope)
– Store data to be used throughout program
• Local Variables
– Variables that are declared within function
– They are accessible only inside the function in which they are declared
– They don’t persist beyond the function’s life time
Functions
• Functions are reusable named blocks of code that perform
specific task or action
• Functions allow you to breakdown your program into smaller,
more manageable pieces making your code more modular,
reusable, and easier to understand
• Functions mainly consists of header and body
– header: int main ()
– body: contained between { and }
• starts with local declarations
• followed by series of statements
• More than one function may be defined
• Functions are executed(invoked) when they are called
Main Function(1)
• Avoid using single-letter variable names unless for loop counters or other similar
scenarios where the purpose is obvious.
Valid/Invalid Identifiers
Valid Invalid
sum 7of9
c4_5 x-name
A_NUMBER name with spaces
longnamewithmanychars 1234a
TRUE int
_split_name AXYZ&
Execution of a C Program(1)
• In order to write and run a given C program, You would be required to
apply the following:
1. Setup the environment by installing the required Integrated
Development Environment(IDE) or Text editors and compilers.
2. Write the C code using the IDE or Text editor and save it with a .c
extension.
3. Compile the program using a C compiler.
– The compiler translates the human-readable source code into machine-readable
object code or executable code. During compilation, the code is checked for syntax
errors and translated into machine code suitable for the target platform.
Execution of a C Program(2)
4. Linking (if necessary): If the program consists of multiple source files or
uses external libraries, linking may be required.
Linking combines the object code generated from individual source files and
resolves references to external symbols, producing a single executable file.
5. Running the Program: Once the compilation and linking processes are
complete, the compiled program is ready to run.
The executable file is loaded into memory, and the operating system allocates
resources such as CPU time and memory for its execution.
Next the operating system transfers control to the starting point of the program,
typically the main() function, and the instructions are executed sequentially.
The program interacts with the operating system, input/output devices, and other
programs as necessary to perform its tasks.
Execution of a C Program(3)
In a given C program, the function main() is executed first. It is the starting
point for the execution of your programs.
Upon termination, the program releases any allocated resources and returns
control to the operating system.
Data Types in C(1)
• Data types determine the type of value to be stored in a given variable, types of
operations to be performed and how much memory should be allocated to that variable
• C supports various types of data types:
Built-in data types: data types that are pre-defined (defined by the creators of the
language) by the programming language.
E.g. Integers, floats
Built-in data types are those data types that can be directly used by the programmer to
declare and store different variables in a program.
They are also known as base types or primary/primitive types
Derived data types: data types that are defined in terms of other data types called
base types. The following are the most common examples of derived data types in
C:
Arrays: contiguous collection of elements of the same data type
Pointers: variables that store memory addresses
Structures: composite data types consisting of members of different types
Unions: similar to structures but share the same memory location for all the elements
Enumerations: contain collections of named constants
Data Types in C(2)
• Built-in Data Types:
Integer types – represent an integer number
– int: integers, typically 4 bytes on most systems
• Variables must be declared before they are used, specifying their data type
int age; //Declaration only. The variable will have a garbage value
• This type of conversion happens when we want to convert from higher data
type to lower data type
variable with lower data type = (lower data type) Expression with a higher data type;
• They are variables that cannot be modified once they are declared in the
program. We can not make any change in the value of the constant variables
after they are defined.
• The data type of the constants can be any of the valid data types in C
• The const keyword is placed at the start of the variable declaration to declare
that variable as a constant.
Constants in C(2)
• We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.
• The constant variables in C are immutable after its definition, i.e., they can be
initialized only once in the whole program.
• After that, we cannot modify the value stored inside that variable.
Formatted Input/Output(1)
• Formatted input/output refers to the conversion of data to and from stream of
characters for printing(or reading) in plain text format
• I/O is done one character(byte at a time)
• stream is a sequence of characters flowing from one place to another
– Input stream: data flows from input devices(keyboard, files, …) to the memory
– Output stream: data flows from memory to output devices (monitor, printer,
files,…)
• Standard I/O streams:
– Standard input stream(stdin): keyboard is the default
• These functions are called formatted I/O functions because we can use format
specifiers in these functions and hence, we can format these functions
according to our needs
Field Specifications(2)
– Width: how many character spaces to use in printing the field (use
minimum spaces, if more needed you can add more). Specifying the field
width is most useful when printing multiple lines of output that are meant to
line up in a table format
Field Specifications(3)
– Precision: for floating point numbers, precision determines how many digits
appear after the decimal point. And the number before the decimal point
determines the width(i.e. the number of digits before the decimal point + number
of digits after the decimal point).
Field Specifications(4)
– Example 3: int numStudents = 1235; float cost = 45,612.35;
printf(“MIT has %d students and the total cost to cover the expenses of the
students is %7.4f Birr per month", numStudents, cost);
Output: ???
– Example 4: char letter=‘Q’;
printf(“%c %c %c”, “*”, letter, “*”);
Output: *Q*
– Example 5: printf(“%s %10s and %-10s”, “Hello”, “Abebe”, “Abeba”);
Output: Hello Abebe and Abeba
Note: In the printf() function, values are converted to proper types while
being executed:
– Example: printf(“%d”,97); produces the integer 97 on the screen
– Example: printf(“%c”,97); produces the character a on the screen
Left Justification (Flags) and Size indicators
For integers, put 0 after % to indicate that the number should pad with 0’s
printf(“%05d”,753);
Produces the output:00753
• They are used to check if the values are equal to each other or
not
y*10
• The ternary operator is a concise alternative to an if-else
statement for simple conditional assignments.
• However, for more complex conditions or when multiple
statements need to be executed, an if-else statement is usually
more readable.
Conditional operator(3)
• Example 2:
Increment and Decrement operator(1)
• In C, ++ and -- are called increment and decrement operators respectively.
• Both of these operators are unary operators, i.e, used on single operand.
But, when used in the postfix notation, the current value of the
variable is used in a given expression and then the operation (the
increment or decrement) will be performed next.
Increment and Decrement operator(3) – Example 1
Increment and Decrement operator(3) – Example 2