0% found this document useful (0 votes)
11 views56 pages

ICS Lecture5 7

The document provides an introduction to the C programming language, detailing its history, evolution, and significance in systems programming. It covers fundamental concepts such as variable declaration, data types, control statements, and the structure of a C program. Additionally, it includes examples of basic C syntax and programming practices.

Uploaded by

Vikas Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views56 pages

ICS Lecture5 7

The document provides an introduction to the C programming language, detailing its history, evolution, and significance in systems programming. It covers fundamental concepts such as variable declaration, data types, control statements, and the structure of a C program. Additionally, it includes examples of basic C syntax and programming practices.

Uploaded by

Vikas Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

ICS - Lecture

Slides are prepared from various sources on the web.


Introduction to C

C source code Compiler

This involves many micro-steps


Welcome to the world of C
• Dennis Ritchie – AT&T Bell Laboratories – 1972
• 16-bit DEC PDP-11 computer
• Widely used today •
• extends to newer system architectures
• efficiency/performance
• low-level access
Welcome to the world of C
• Evolved over the years:
• 1972 – C invented
• 1978 – The C Programming Language published; first specification of
language
• 1989 – C89 standard (known as ANSI C or Standard C)
• 1990 – ANSI C adopted by ISO, known as C90
• 1999 – C99 standard
• mostly backward-compatible
• 2007 – work on new C standard C1X
Welcome to the world of C
• Systems programming: Faster Code
• OSes, like Linux
• microcontrollers: automobiles and airplanes
• embedded processors: phones, portable electronics, etc.
• DSP processors: digital audio and TV systems
• Derivatives: C++, Objective C, C#
• Influenced: Java, Perl, Python (quite different)
Welcome to the world of C
• Handle with care.
• Always run in a debugger like gdb (more later. . . )
• Never run as root
• Never test untested code on the college servers
Welcome to the world of C …
• Before you start the program
• Have an environment - gcc compiler or C IDE
• Linux users - inbuilt gcc complier
• IDE: Eclipse, VC++, KDevelop, Xcode
Welcome to the world of C….

#include <stdio.h>

int main (void)


.c extension
{
printf (“Hello world”);
}
Structure of a .c file
• /* Begin with comments about file contents */
Insert #include statements and preprocessor definitions
Function prototypes and variable declarations
Define main() function {
Function body
}
Define other function
{
}
Comments
• Comments: /∗ this is a simple comment ∗/
• Can span multiple lines
/∗ This comment spans
multiple lines ∗/

• Completely ignored by compiler


• Can appear almost anywhere
/∗ hello.c −− our first C program */
Comments
• Comments: /∗ this is a simple comment ∗/
• Can span multiple lines
/∗ This comment spans
// is also used for commenting (c++ style)
multiple lines ∗/

• Completely ignored by compiler


• Can appear almost anywhere
/∗ hello.c −− our first C program */
The #include macro
• Header files: constants, functions, other declarations •
#include <stdio.h> – read the contents of the header file
stdio.h
• stdio.h: standard I/O functions for console, files
#include <stdio .h> /∗ basic I /O facilities ∗/
The #include macro
• Header files: constants, functions, other declarations •
#include <stdio.h> – read the contents of the header file
stdio.h
• stdio.h: standard I/O functions for console, files
#include <stdio.h> /∗ basic I /O facilities ∗/
stdio.h – part of the C Standard Library
other important header files: ctype.h, math.h, stdlib.h, string.h,
time.h
Welcome to the world of C….

#include <stdio.h> Header file

int main (void) Usually the entry point of a c program

{ Library function,
uses write system call
printf (“Hello world”);
Statement terminator
}
Formatted output
More printing … (code and see)
#include <stdio.h>
int main(void)
{
printf ("Hello, World! ") ;
printf ("Hello \n World! \n") ;
}
\n character
Some more printing
#include <stdio.h>
int main(void)
{
printf ("Hello, World! \n") ;
printf ("Hello \n World! \n") ;
printf ("Hell\no \t World! \n") ;
}
\t character
Int main (void) vs void main()
• int main() can be called with any number of arguments,
but int main(void) can only be called without any argument.
• Although it doesn’t make any difference most of the times,
using “int main(void)” is a recommended practice in C.
• Will discuss more when we will discuss functions
Reading values from keyboard

#include <stdio.h>
int main(void) {
int num ;
scanf ("%d", &num) ;
printf (“No. of students is %d\n”, num) ;
}
Common GCC file types
• .c -> C source code file.
• .h -> Header file contained in the program.
• .o -> Target file after compilation.
• .out -> Executable files, which do not have a fixed suffix. The
system distinguishes executable files from inexecutable files
based on file attributes. If the name of an executable file is
not given, GCC generates a file named a.out.
Variables
• Must declare variables before use #include <stdio.h>
int main(void) {
• Variable declaration: int n; float phi;
int num ;
• int - integer data type
scanf ("%d", &num) ;
• float - floating-point data type printf (“No. of students is
• Many other types %d\n”, num) ;
}
• What are variables?
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height: ");
scanf("%f", &height);
printf("Enter your name: ");
scanf("%s", name);
// note that this reads only a single word
printf("Your name is %s, you are %d years old, and your height is %.2f meters.\n", name, age, height);
return 0;
}
Variables
• Variables are containers for storing data values, like numbers
and characters in the memory. Can we change the content of a
container?

You can imagine


something like
this

How big container do we need to pack the content? Container type / Datatype
Variables
• A variable is a named storage location in the computer’s
memory.
• If we want to hold some value in memory for later use, we need to
use as variable.
• Variables have 3 characteristics:
• Name – the name we use in our code to refer to the memory location.
• Type – characteristic that defines what legal values the variable can
hold.
• Value – what is actually held inside of the memory location.
Data Types
• Types of Data Types in C - The C programming language has
two basic data types:
• Primary
• Derived
Datatypes: some built-in/primitive datatypes
• The datatype of a variable determines how much space it occupies in
memory and how the bit pattern stored is interpreted.
What would happen in 32 bit environment
What would happen in 32 bit environment
• In the table, the integer is 16-bit or 2 bytes wide. Thus, the
compiler is also 16-bit or 2 bytes wide.
• If the compiler was 32-bit wide, the int type size would have
been about 32-bits or 4 bytes.
• However, this might not be the case every single time.
• It is also possible that the integer size is 32-bits or 4 bytes
for a 64-bits processor. It entirely depends on the type of
compiler.
What would happen in 32 bit environment
• Int: -2,147,483,648 to 2,147,483,647
The C Character Set
• The C language alphabet
• Uppercase letters ‘A’ to ‘Z’
• Lowercase letters ‘a’ to ‘z’
• Digits ‘0’ to ‘9’
• Certain special characters:
! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank

A C program should not contain anything else


How to keep variable names
• Character Set: uppercase and lowercase letters, digits (0-9),
and underscores (_). Variable names must begin with a letter
or an underscore. They cannot start with a digit.
• Length: No specific limit on length - short and representative
• Case Sensitive: Variable names in C are case-sensitive
• Keywords: Variable names cannot be the same as C keywords
(reserved words), such as int, return, if, while, etc.
• No Special Characters: !, @, #, $, %, ^, &, *, -, +, =, |, \, :, ;, ,, <, >, ?…
Attendance Quiz - (correct/incorrect)

https://tinyurl.com/iitjics138

• int money$owed

Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count

Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count
• int score2

Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count
• int score2
• int 2ndscore
Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count
• int score2
• int 2ndscore
• int long
Pop Quiz - (correct/incorrect)

• int money$owed; (incorrect: cannot contain $)


• int total_count (correct)
• int score2 (correct)
• int 2ndscore (incorrect: must start with a letter)
• int long (incorrect: cannot use keyword)
#include <stdio.h> Format Specifiers
int main () Declaring variables
{ A few of them are as follows.
%c --- character
int a, b, c; %d --- Signed integer (%7d)
c = a+b; %f --- Float values (%.3f)
%lf --- Long double
a = 5; %s --- Strings
%o --- Octal
b = 6; Etc…………….
printf (“The sum is %d”, c);
} Assigning some value in the variables
Void
• Is a type, but not a data type.
• Functions can have a void return type, which means they do
not return a value.
• The parameter list of a function can also be void. It means
the function takes no parameters.
• For now, you can think of void more as a
placeholder for “nothing”.
Let us write some programs
• Convert Fahrenheit to Centigrade
• How you would go about it?
Fahrenheit to Centigrade
#include<stdio.h>
int main()
{
float cent, fahr;
scanf(“%f”,&fahr);
cent = ((fahr-32)*5/9);
printf("%f F = %f C", fahr, cent);
return 0;
}
Structure of a C program

• A collection of functions (we will see what they are later)


• Exactly one special function named main must be present.
Program always starts from there
• Each function has statements (instructions) for declaration,
assignment, condition check, looping etc.
• Statements are executed one by one
Largest of two numbers
• How you would go about it?
Largest of two numbers
#include <stdio.h>
void main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y) printf(“Largest is %d\n”,x);
else printf(“Largest is %d\n”,y);
}
What does this do?
#include <stdio.h>
int main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y)
{
printf("Largest is %d\n",x);
printf("Largest is %d\n",y);
}
}
Operators
Write an algorithm to select what dress is
appropriate for a given outside temperature
Write an algorithm to select what dress is
appropriate for a given outside temperature
Control Statements
• Allow different sets of instructions to be executed
depending on whether certain conditions is evaluated
to be true or false.
• Also called branching.
• A Condition can an expression
• Expression = non-zero value ---> True
• Expression = Zero value ------> False
Syntax

if(expression)
{
//code to be executed
}
If-else: Control Statements (Cont.…)

Syntax

if(expression)
{
//Statements
}
else
{
//Statements
}
• IF without an else is possible.
• Else without an if is not possible.
if-else-if ladder: Control Statements (Cont.…)
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements ***Dangling else problem
}
Dangling else problem
Initialize k=0 and o=0 Initialize k=4, o=5, ch=7
if(ch>=3) if(ch>=3)
if(ch<=10) {
k++; if(ch<=10)
else Print k}
o++; else
Print o
Dangling else problem

Initialize k=0 and o=0 Brackets and


Indentation
if(ch>=3)
if(ch<=10)
k++;
else If - else if -
Else
o++;
Determine dress
• if (temperature > 40)
• printf(“wear shorts”);
• else if (temperature >25)
• printf(“ideal weather - wear nice dress”);
• else if (if temperature > 10)
• printf(“chilly weather - wear warm cloths”);
• else
• printf(“stay inside”);
Determine dress
• if (temperature > 40) & weather = windy
• if (temperature > 40) & weather = sunny
• if (temperature > 40) & weather = humid

• if (temperature > 40)


• If weather = sunny
• If weather = humid
• If weather = windy
Nested if-else: Control Statements (Cont.…)

if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{ Any levels of nested if-else is possible.
statement-block 3;
}
Operators in C

Operators are used to perform


operations on variables and values.

increments/ decrements the values by 1

mathematical operations such as add, sub, etc.


checks the relationship between two operands
An expression containing logical operator returns either 0 or 1 depending
upon whether expression results true or false.
Performs bit-level operations
Unary operator that returns the size of data
Assignment operator is used for assigning a value to a variable

Conditional - similar to if-else

You might also like