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

Introduction to Programming in C

The document provides an introduction to the C programming language, detailing its history, characteristics, and structure. It covers essential concepts such as data types, variables, functions, and the execution process of a C program. Additionally, it explains syntax rules, identifier conventions, and formatted input/output operations in C.

Uploaded by

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

Introduction to Programming in C

The document provides an introduction to the C programming language, detailing its history, characteristics, and structure. It covers essential concepts such as data types, variables, functions, and the execution process of a C program. Additionally, it explains syntax rules, identifier conventions, and formatted input/output operations in C.

Uploaded by

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

Mekelle University

Mekelle Institute of Technology


Department of Information Technology
Programing in C(IT1202) Lecture Materials
Topic: Introduction to Programming in C
Introduction to C(1)
 C is a high-level programming language developed by Dennis Ritchie at Bell
Laboratories in the early 1970s.

 It is a general-purpose, procedural language with a syntax influenced by the B


language.

 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.

 Structured: C supports structured programming constructs such as loops, conditional


statements, and functions, making it easy to write and maintain large programs.

 Portable: C programs can be compiled and run on different platforms with minimal
changes, thanks to its low-level features and standard libraries.

 Powerful: C provides low-level access to memory, enabling efficient manipulation of


data and hardware interaction.

 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)

#include <stdio.h> Preprocessor Directive

int x; Global Declaration

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)

• Every program has one function main

• Header for main: int main ()

• Program is the sequence of statements between the { }


following main

• Statements are executed one at a time from the one


immediately following to main to the one before the }
Main Function(2)
Comments
• Are used to give extra information to the reader of about the code.
They play a crucial role in enhancing the readability and
understandability of your code
• Comments are also placed at the beginning of your program so as to
give information about the purpose of the program, the author(s) and
copyright information
• They are also helpful to test and debug your code
• Comments are ignored by compiler (that is it doesn’t treat them as
parts of your program)
• Any text that you find in your program between /* and */ is a C
comment
• We have two types of comments in C:
– Single line comments represented by : //
– Multiple line comments represented by : /* … */
Comment Example
#include <stdio.h>

/* This comment covers


* multiple lines
* in the program.
*/

int main () /* The main header */ {


/* No local declarations */

printf(“Too many comments\n”);


} /* end of main */
Syntax of C Program(1)
• C is a case-sensitive language, meaning uppercase and
lowercase letters are treated differently.

• Statements in C are terminated by semicolons (;).

• Blocks of code are enclosed within curly braces ({ }).

• Indentation is not required for the compiler but is used to


improve code readability.
Syntax of C Program(2)
• Rules that define C language
– Specify which tokens are valid
– Also indicate the expected order of tokens
• Some types of tokens:
– Reserved words: include, printf, scanf, int, float, if, else,
switch, while ...
– Identifiers: x, y ...
– Literal constants: 5 ‘a’ 5.0 ...
– Punctuation: { } ; < > # /* */
Reserved Keywords in C
• The following list indicates the reserved keywords in C:
• auto , else , long , switch , break , enum , register ,
typedef , case , extern , return , union , char , float
, short , unsigned , const , for , signed , void ,
continue , goto , sizeof , volatile , default , if ,
static , while , do , int , struct , double
Identifier(1)
• Identifiers are names given to various program elements such
as variables, arrays and function in C
• Rules for identifiers in C:
– Can consist of letters (both uppercase and lowercase), digits[0-9], and
underscores (_).
– They must begin with a letter (uppercase [A-Z] or lowercase [a-z] ) or an
underscore(_).
– However, it's a convention to avoid using leading underscores, especially for
global identifiers, as they might conflict with system names.
– Can be of any length, but only the first 31 characters are significant.
– C is case-sensitive, meaning uppercase and lowercase letters are treated as
distinct. For example, "myVariable" and "MyVariable" are considered
different identifiers.
Identifier(2)
• Rules for identifiers in C:
– Identifiers cannot be the same as C keywords (reserved words), as
they have predefined meanings in the language

– Special characters like !, @, #, $, %, ^, &, *, etc., cannot be used


within identifiers.

– Identifiers cannot contain spaces. If you need to represent multiple


words, you can use camelCase or snake_case convention,
• camelCase - the first word is lowercase and subsequent words are capitalized

• snake_case – the first word is lowercase and separated by underscores


Identifier(3)
• Rules for identifiers in C:
– While not enforced by the compiler, it's good practice to follow
standard naming conventions for readability. For example:
• Use meaningful names that describe the purpose of the identifier.

• For variables and functions, use camelCase or snake_case.

• For constants, use uppercase with underscores separating words (e.g.,


MAX_VALUE).

• 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.

 And each statement in main function is executed from first to last

 Executed in order (first to last)

 Changes made by one statement affect later statements

6. Termination: the program continues to execute until it reaches the end or


encounters a termination condition, such as reaching a return statement in the
main() function or encountering an error.

 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

– Unsigned int – stores no negative values in the range of 0 – 65, 536

– short: short integers, usually 2 bytes.

– long: long integers, typically 4 or 8 bytes.


– Example: 29, -50, 1947, 50384

 Floating-Point types – represent numbers in decimal format


– float: single-precision floating-point numbers, typically it occupies 4
bytes and it provides approximately 7 decimal digits of precision

– Example: float singlePrecision = 3.1415987;


Data Types in C(3)
– double: double-precision floating-point numbers, typically it occupies 8
bytes and it provides approximately 15 decimal digits of precision.
– long double: extended-precision floating-point numbers, typically it
occupies 10 bytes of memory and it provides approximately upto 20
decimal digits of precision.
– Example: double doublePrecision = 3.141592653589793;
 Character types – represent character values like a single letter, digit or
special characters
– char: a single character, typically 1 - 2 byte.

– Example: ‘A’, ‘$’, ‘g’, ‘5’

 Boolean data type – It is a logical type of built-in data type. It represents


only two values: true or false

– The default value of a Boolean data type is false.


Variables
• Variables are named memory location that are used to store values

• Variables must be declared before they are used, specifying their data type

• Variables can be initialized during declaration or later in the program

• Variables can be declared in global or local declaration scopes

• Syntax: Data Type Name_Of_Variable;


• Examples:

int age; //Declaration only. The variable will have a garbage value

float pi=3.14159; //Declaration and initialization

char grade=‘B’; //Declaration and initialization


Multiple Variable Declarations
• We can create multiple variables of the same type in one
statement:
• Example: int x, y, z;
• This is a shorthand for the following code:
int x;
int y;
int z;
• Stylistically speaking, the latter is often preferable
• Can provide one value for variables initialized in one statement:
int x, y, z = 0;
• Each variable is declared and then initialized with the value of 0
Data Type Conversion(1)
• Converting one datatype into another is known as type casting or, type-
conversion.
• Type conversion happens during time of compilation. It is only performed to
those data types where conversion is possible.
• In type conversion, the destination data type can’t be smaller than the source
data type.
• There are two types of type conversion:
– Implicit Conversion : it is done by the compiler itself without the need of
external trigger from the user. All the data types of the variables are
upgraded to the data type of the variable with the largest data type.
Data Type Conversion(2)
– Explicit Conversion : it is also called type casting and it is user defined
• The user can typecast the result to make it of a particular data type.

• This type of conversion happens when we want to convert from higher data
type to lower data type

• The syntax for type conversion in C Programming is:

variable with lower data type = (lower data type) Expression with a higher data type;

• Example: double x=356.899;

int sum = (int) x+5; //Explicit conversion from double to int


Constants in C(1)
• The constants in C are the read-only variables whose values cannot be
modified once they are declared in the C program

• 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

• In C language, the const keyword is used to define the constants.

• 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

– Standard output stream(stdout): monitor is the default


• stdio.h – contains basic input/output functions like printf() and scanf()
Formatted Input/Output(2)
• Formatted input/outputs functions are used to take various inputs from the user
and display multiple outputs to the user.

• 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

• All text I/O we do is considered formatted I/O


Formatted Output
• The printf() function is used to print formatted output
• Syntax: printf(format_string, list_ of_expressions);
– format_string is the layout of what is being printed
– list_of_expressions is comma separated list of variables or expressions
yielding results to be displayed in the output
• Example 1: printf(“Welcome to PIC! \n”);
Gives this output: Welcome to PIC!
• Example 2: printf(“Welcome to\n PIC! \n”);
Gives this output: Welcome to
PIC!
• Successive printf commands cause output to be added to previous output
• Example:
printf(“Hi, how “);
printf(“is your practice in programming going?”);
Gives this output: Hi, how is your practice in programming going?
Field Specifications(1)
• Format string may contain one or more field specifications
– Syntax: %[Width][Prec][Size]Code
– Codes:
• c - data printed as character
• d - data printed as integer
• u – data printed as unsigned integer
• f - data printed as floating-point value
• e – data printed as floating-point exponential notation
– For each field specification, have one data value after format string,
separated by commas
– Example: printf(“%c %d %f\n”,’A’,35,4.5);
Gives the output: A 35 4.50000
– Can have variables in place of literal constants (value of the variables will
be printed)
i

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

– Example 1: int numStudents = 1235;

printf(“MIT has %d students", numStudents);

Output: MIT has 1235 students

– Example 2: int numStudents = 1235;

printf(“MIT has %10d students", numStudents);

Output: MIT has 1235 students


i

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).

– Example 1: float cost = 456.1235;

printf(“Your total cost for this month is %7.4f Birr", cost);

Output: Your total cost for this month is 456.1235

– Example 2: float cost = 456.1235;

printf(“Your total cost for this month is %7.3f Birr", cost);

Output: Your total cost for this month is 456.124


i

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

 Put - after % to indicate value is left justified


printf(“%-5d%-8.3fX\n”,753,4.1678);
Produces an output: 753 4.168 X

 For integers, put 0 after % to indicate that the number should pad with 0’s
printf(“%05d”,753);
Produces the output:00753

 Size indicators: indicate the size of the data being processed


– Use hd for short integers
– Use hu for unsigned short integers
– Use ld for long integers
– Use lu for unsigned long integers
– Use lf for long floating point numbers
– Use Lf for long double floating point numbers
Formatted Input(1)
• The function scanf() is used to accept formatted input from the keyboard
• Syntax: scanf(format_string, address_list);
– format_string a string with one or more field specifications. It is the same as
with the printf()

– characters are read from keyboard and stored in variables. Therefore, we


specify the address of these variables in the address_list

– If x is a variable &x specifies the “address of x”. It tells the computer to


store the value read at the location of the variable
Formatted Input(2)
•The data type read, the conversion specifier, and the variable used need to
match in type
•Conversion specifiers for input are mostly the same as for output but there
are some small differences: use %f for float but %lf for double and long
double
•White space is skipped by default in consecutive numeric reads. But it
is not skipped for character/string inputs.

– Example: char cVar;


int dVar;
float fVar;
» scanf(“%c %d %f”, &cVar, &dVar, &fVar);
• The example given above reads first a single character, then an integer, and
finally a floating point number from the keyboard
Formatted Input(3)
• Conversion process continues until:
– end of file reached
– maximum number of characters processed
– non-number character is found while numbers are processed
– an error is detected (inappropriate character)
• We must specify field specification for each variable and an address
specifier for each for each field specification.
• Any character other than whitespace must be matched exactly
• Prompting for Input:
– Using output statements to inform the user what information is needed:
int number;
printf(“Enter an integer:”);
scanf(“%d”, &number);
– Output statement provides a cue to the user:
Enter an integer: user types here
Operators in C(1)
• An operator in a programming language is a symbol that tells the
computer to perform specific mathematical, relational or logical
operation and produce some result.

• Arithmetic operators: are operators that are used to perform


mathematical calculations

• Few of the important arithmetic operators available in C programming


language are: +, -, *, / and %.

• The % operator is known as modulo operator and it gives the


remainder of a given integer division
Assignment operator(1)
• Assignment operator - the most common assignment operator is
the equal symbol =
• This operator assigns the value in right side to the left side.
• For example:
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant
Note: During assignment, the value on the left side must be a variable
Assignment operator C(2)
Relational operators(1)

• Relational operators – are operators that are used to determine


the relationship between the values of the given variables

• They are used to check if the values are equal to each other or
not

• Following table lists down few of the important relational


operators available in C. Assume variable A holds 10 and
variable B holds 20, then:
Relational operators(2)
Logical operators(1)
• Logical operators help us in taking decision based on certain
conditions.
• Suppose we want to combine the result of two conditions, then logical
AND and OR help us in determining the final result.
• The following table shows all the logical operators supported by C
language. Assume variable A holds 1 and variable B holds 0, then:
Conditional operator(1)
• Conditional operator is also known as ternary operator
• It is the only operator in C that takes three operands and consists of two
symbols in one line.
• It is used for decision making purposes. It is the short hand way of
writing simple if-else statements
• The syntax for the conditional operator is :
Condition ? Expression1 : Expression2 ; /* Condition is a Boolean expression that
must be evaluated. If condition is true, then Expression 1 will be executed. If not
Expression2 will be executed */
Conditional operator(2)
• Example 1: int y = 10;

int ternary_variable = (value<0)? –y*10 : y*10

– If value is less than zero, ternary_variable is assigned –y*10

– If value is greater than zero, ternary_variable is assigned

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.

• ++ adds 1 to the operand and -- subtracts 1 to the operand respectively.


• The increment and decrement operators can be used in a prefix
notation(like: ++var), or in a postfix notation (like var++)

• For example: Let a=5 and b=10


a++; //postfix increment  a becomes 6
a--; // postfix decrement  a becomes 5
++a; // prefix increment  a becomes 6
--a; // prefix decrement  a becomes 5
Increment and Decrement operator(2)
• When increment or decrement of a value of a variable is used in an
expression, there is a difference in the prefix notation and postfix
notation

 When used in a prefix notation, the operation (the increment or


decrement) is performed before it is used in a given expression

 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

You might also like