SlideShare a Scribd company logo
1 of 144
C for Engineers
Julie Iskander,
MSc. Communication and Electronics
Course Outlines
•
•
•
•
•
•

Introduction to Programming
C Program
Data Types, Variable and Constants
Control Statements and loops and functions
Memory Management and Pointers
Structures
Introduction
What is a Computer Program?
• Computers are dumb machines.
• A Computer Program is a set of instructions, written in a
language the computer understands, to tell the computer
what to do to solve a problem.
• The approach or method used to solve a problem is called an

algorithm
• Example:
• How to write a program to tell if a number is odd or even?
Programming Language
• Machine Language
• Low-level languages
• High level languages
Compilers
• To support a higher-level language, a special computer
program must be used that translates the statements of the
high-level language program into the particular instructions of
the computer.
• A compiler analyzes a program and then translates it into a
form that is suitable for execution on your particular computer
system.
• Types of errors:
• Syntax error  detected by compiler
• Logical error  is not detected by compiler, but makes code give
unpredicted results.
Programming Methodologies
• Linear Programming
• Structural Programming
• Object Oriented Programming
Software Development Life
Cycle
•
•
•
•
•

Analysis
Design
Implementation
Testing
Maintenance
Dennis Ritchie (1941-2011)
• Designer and original
developer of the C
programming language.
• A central figure in the
development of Unix.
• Was awarded the Turing
Award in 1983, and the
National Medal of Technology
in 1999.
• "Ritchie's influence rivals
Jobs's; it's just less
visible," James Grimmelman
observed on Twitter. "His
pointer has been cast to void
*; his process has terminated
with exit code 0."
C Programming Language
• C is a general-purpose programming language initially
developed by Dennis Ritchie between 1969 and 1973 at AT&T
Bell Labs.
• Its design provides efficient mapping to typical machine
instructions, thus substitutes assembly language,
• Portable, as it is not difficult to write programs that can be
run without change on a variety of hardware
• Most of the Linux and UNIX operating systems are written in
C.
C is a “higher-level language,”
yet it provides capabilities that
enable the user to “get
in close” with the hardware
and deal with the computer on
a much lower level.
“PROGRAMMING IN C”, THIRD EDITION, STEPHEN G. KOCHAN
C Compiler
*.c

compiler

.obj

linker

.exe

Compilers translate an entire file of code all at once, rather than line by
line.
Generate all error messages
Creates an intermediate file, waiting to be linked to any external libraries
needed, to create a final executable file
Linker combines your object file with object files already found in the
libraries.
C Program
Structure
C Program
PreProcessor

Program Body

#include <stdio.h>

int main()
{
printf(“Hello C ”);
return 0;
}
#include directive
• Tells the compiler to insert another file at this location of your
source code.
• The new inserted code is compiled with the rest of the source
code.
• Also include header files (*.h).
• A header file is a file that contains the function prototype of
the functions defined in the library file before compilation, the
compiler will add the header file contents to the source code.
At compilation, the compiler can check function signatures
against syntax errors.
Program Body
Entry Point of the
program. A program
must contain atleast
on function, main()

int main()
{
variable or constant declaration;
statements;
return 0;
}

All variables
must be
declared before
any statement
is executed
C Comments
• Not executable statement, documents the code
• Ignored by compiler
• Single line Comment
// this is a single line comment

• Multi – line Comment
/* This is a longer comment
That spans across multiple lines
……………………….. */
Data types, Variables ,
Constants
Data types
• There are 5 fundamental data types
1.
2.
3.
4.
5.

char (1 byte)
int (2 bytes)
float (4 bytes)
double (8 bytes)
Void
• Size may differ from platform to another

• Can add type modifier to the data types to alter its meaning
(unsigned, signed, long, short)
• Example
• Signed char  0 to 255
• unsigned char  -127 to 127
Variables
• A place to store data, for further usage.
• Declaring Variables:
• datatype variable_name
• datatype variable_list

• Example:
• int x;
• char a,b,c,e;

• C doesn’t initialize variables.
• After declaring a variable, it can be used multiple times
Variables
Local Variables

Global Variables

• Declared inside a
function
• Available only for the
function.
• Ends with the
function, closing
brackets of the function

• Declared out of any
function
• Available for all functions
• Not recommended to
use it extensively.
Constants
• A fixed value, that can’t be changed at any part of the program
• There are two ways to define a constant value
• As a macro, in the preprocessor using define

• #define PI 3.14
• In a program body

• const int pi=3.14;
• Must be initialized when declared
Statements
• Are executable lines of code
• Ends in ;
• Can be a input statement, expression or operation or output
statement
I/O statements
• Output function: display the results on the screen
• printf()
• printf(“string”,*,data+);
• Example:
printf(“Hello”);
int x=3;
printf(“x is %d”,x);

• Format specifiers
•
•
•
•

%d integer
%f float
%c char
%lf double

• putchar(): puts a character on the screen.
• Example:
• putchar(‘a’) ; or putchar(23);
I/O statements
• Input function: wait for user to enter values and save it.
• scanf(“format-specifier”, address -of-var):
Wait for user to input, must specify the data type of the input
(format specifier) and the address to store value in
• getchar()
Reads one character only from keyboard and wait for carriage
return, character is printed to screen
• getch() (only bc)
Reads one character only from keyboard without waiting for
carriage return, character is not printed to screen
• getche() (only bc)

Reads one character only from keyboard without waiting for
carriage return, character is printed to screen
Operators
Operators
Operators
C Memory Managment
Stack

Heap

Uninitialized data
segment

Global and static
Variables Section
(Initialized Data
Segment)
Executable Code
Section
(Code Segment)
Assignments
• Assignment 1: The history of programming languages.
• Assignment 2: Interpreter Versus Compiler
• Assignment 3: What’s the output of the following:
int a=25, b=3;
printf("%d", a/b*b);
Why?
Lab
• Install Borland C 3.1 or Cygwin
• Write hello.c to print Hello world
• Write a program to print the following with the same format
***********
**Hello all**
***********
with one printf statement. Use escape sequences like n,t,…..etc.
• Fix errors in error1.c and error2.c.
• Write a program to ask user to enter the number of the day in a
year and the program will output the day and month. Assume all
month has 30 days.
• Try writing a function for the previous assignment
• Try casting and operator precedence
Branching
if statement
if(condition)
{
statements
}
else
{
statement
}
• Write a program to specify if a number is odd or even
int main()
{
int num;
printf(“Enter a number: ”);
scanf(“%d”, &num);
if(num%2)
{
printf(“Odd”);
}
else
{
printf(“Even”);
}
return 0;
}
Nested if
if(condition)
{
statements
}
else
{
if(condition)
{
statement
}
else
{
statement
}
}

if(condition)
{
statements
}
else if(condition)
{
statement
}
else
{
statement
}
• Write a program to print grade of students according to his
marks
int main()
{
int mark;
printf(“Enter your mark: ”);
scanf(“%d”, &mark);
if(mark>=90)
printf(“A”);
else if(mark>=80)
printf(“B”);
else if(mark>=70)
printf(“C”);
else
printf(“Failed”);
return 0;
}
switch................case
switch(expression)
{
case const1:
{
statement;
break;
}
case const2:
{
statement;
break;
}
case const3:
{
statement;
break;
}
default:
{
statement;
}
}
Write a program to print marks range of
students according to his grade
int main()
{
char mark;
printf(“Enter your mark: ”);
scanf("%c",&mark);
switch (mark)
{
case ‘A’:,
printf(“Marks between 100
and 90”);
break;
}
case ‘B’: ,
printf(“Marks between 90
and 80”);
break;
}

case ‘C’:
{
printf(“Marks between 80
and 70”);
break;
}
default:
{
printf(“less than 70”);
}

}
return 0;
}
break
• What if we forget a break in any case?

Fall through
• All sequential cases till the first break or end of cases will be
evaluated
Looping
Looping
• Is repeating a block of code for a specific times or until a
condition is satisfied.
• Loops can be terminated using break statement, or an
iteration skipped using continue statement.
for loop
for( initialization ; condition ; increment )
{
statements to be repeated;
}
• Initialization is a statement executed once at the start of the
loop.
• Condition is evaluated before every iteration, to decide to go
on or quit the loop, must evaluate to true/false
• Increment is a statement executed at the end of each iteration
• Used for repeating code a specific number of times
• Write a program to print numbers from 1 to 100
int main()
{
int i;
for(i=1; i<=100 ;i++)
{
printf("%dn",i);
}
return 0;
}
• What’s the output?
int main()
{
int i;
for(i=1; i<=100 ;i++)
{
if(i==10)
continue;
printf("%dn",i);
}
return 0;
}
• What’s the output?
int main()
{
int i;
for(i=1; i<=100 ;i++)
{
printf("%dn",i);
if(i==10)
break;
}
return 0;
}
• What’s the output?
int main()
{
int i;
for(i=1; i<=100 ;i++)
{
if(i==10)
break;
printf("%dn",i);
}
return 0;
}
• What’s the output?
int main()
{
int i=0;
for(; ;)
{
i++;
printf("%dn",i);
}
return 0;
}
• Write a program to take a character and print it till z is
entered?

int main()
{
char c;
for(c=0; c!='z';)
{
printf("Enter a character");
c=getchar();
getchar();
}
return 0;
}

Why do we need to add another getchar()?
• Write a program to calculate the average of marks of 10
students
int main()
{
int i, mark ; int sum=0, avg;
for(i=0; i<10 ;i++)
{
printf("Enter a student mark : ");
scanf(“%d”, &mark);
sum+=mark;
}
avg=sum/10;
printf(“Average of student marks is %d”,avg);
return 0;
}
Nested for loops
What’s the output?
int main (void)
{
int n, number, triangularNumber, counter;
for ( counter = 1; counter <= 5; ++counter ) {
printf ("What triangular number do you want? ");
scanf ("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
triangularNumber += n;
printf ("Triangular number %i is %inn", number,
triangularNumber);
}
return 0;
}
while loop
while(condition)
{
statements to be repeated;
}
• Used for repeating a block of code until a condition is met, the
condition is tested before executing the block of code.
• The block of code can never be executed
int main()
{
int n,x,i=1,multi=1;
printf(“Enter x:”); scanf(“%d”,&x);
printf(“Enter n:”); scanf(“%d”,&n);
while(i<=n)
{
multi*=x; i++;
}
printf(“y is %d”,multi);
return 0;
}
do…….while loop
do
{
statements to be repeated;
} while(condition);
• Used for repeating a block of code until a condition is met, the
condition is tested after executing the block of code.
• The block of code is executed at least once
What is the error in
this code?

int main()
{
int n,x,i=1,multi=1;
printf(“Enter x:”); scanf(“%d”,&x);
printf(“Enter n:”); scanf(“%d”,&n);
do{
multi*=x; i++;
} while(i<=n);
printf(“y is %d”,multi);
return 0;
}
Function
Functions
• Is a block of code, that does a specific task.
• Each program has atleast one function , main
• Functions reduce duplicate code and make maintenance and
modification easier and quicker
• Any function has:
•
•
•
•

Function name
Return type
List of input arguments
body
Functions
• Function definition

Return_type fun_name(list of args)
{
function body
return statement
}
• A function can be defined before the main.
• If defined after main, add a signature before the main. Used
by compiler to check for syntax errors.
• The return statement terminates the function and returns
control to the calling function, is used to return a value
Write a function to print a message
#include <stdio.h>
void sayhi(void);
int main()
{
int a,b,y;
sayhi();
}

void sayhi(void);
{
printf(‘hi from function’);
}
Write a function to add 2 numbers
#include <stdio.h>
int add(int x, int y);
int main()
{
int a,b,y;
printf(“enter 2
numbers”);
scanf(“%d”, &a);
scanf(“%d”, &b);
y=add(a,b);
printf(“the sum is %d”,y)
}

int add(int x, int y)
{
int z;
z=x+y;
return z;
}
What happens in the
memory during
execution?
Passing values to a function
• Call by value
• Where the whole data type is sent to the function and stored as a
local variable to the function, a copy is made.
• Changes done in the function as no effect on the original
variables of the calling function

• Call by address
• Only the address of the argument is sent and stored with the
function
• Changes in the function affects the original variable in the calling
function as it is referenced by its address
• The calling and called functions access the same memory address
Call by address
• Both references the same memory location.

Calling function
x

Called function
Address
of x
Call by value
• Each has it’s own version of the argument.

Calling function
x

Called function
x
Assignments
• Assignment 1: What is a conditional operator or ? Operator ?
• Assignment 2: What are the pros and cons of using call-byvalue and call-by-address?
Lab
• Fix the errors in error1.c and error2.c
• Write a function to calculate the factorial of n, use this function in
main.
• Write a function to reverse the digits in a given number, use this
function in main.
• Write a function that draws a MagicBox table, given its
dimension, use function gotoxy to e able to draw it on the screen.
• Write a program that inputs 5 numbers then prints out the min
and max.
Magic Box
6

1

8

7

5

3

2

9

4

• The size must be odd eg. 3x3, 5x5, 7x7, …………….
• Number 1 is put in row= 1 and col = (size+1)/2
• Numbers from 2 till size*size are put acc. to the
following rule
• If(number-1)%size ==nonzero
• row-1 and col-1
• Or else
• row+1
Static Variables
and Functions
Scope Rules
• All functions are global , no nested functions in C
• A function’s code is private to the function, can’t be accessed by
other functions
• Variables declared inside a block of code, is local to that block.
They’re destroyed at the end of the block of code.
• The input arguments of a function are local variables to it, declared
in the definition of the function.
void func1()
{
int x;
x=10;
}

void func2()
{
int x;
x=-1999;
}

• The variable x is declared twice, with no relation to each other. Each
one is stored in a separate memory location and func1 can’t access
the x in func2.
Scope Rules
• Global variables are declared out of all functions and can be
accessed by all.
What is the output?
int count;
int main()
{
count=100;
printf("In main, count is
%dn", count);
func1();
printf("After func1 call in
main count is
%dn", count);
}

void func1()
{
printf("In func1, count is %dn",
count);
func2();
printf("In func1 after func2 call,
count is %dn", count);
}
void func2()
{
int count=2;
printf("In func2, count is %dn",
count);
}
Static Variables
• Are permanent variables within their own functions or file.
• Not accessible to functions outside their function.
• Maintain their values between function calls.
What is the output?
int main()
{
printf(“series is %d ", series());
printf(“series is %d", series());
printf(“series is %d", series());
}

int series()
{
int num=0;
num=num+23;
return num;
}
What is the output now?
int main()
{
printf(“series is %d", series());
printf(“series is %d", series());
printf(“series is %d", series());
}

int series()
{
static int num=0;
num=num+23;
return num;
}
Recursion
Recursive Functions
• A function that calls itself.
• Must contain a condition, to ensure a finite execution.
• Example: factorial function
• 5! = 5*4*3*2*1

• Using for loop
int t=5, ans=1;
for(; t>=1;t--)
{
ans*=t;
}

• 5! = 5*4! = 5*4*3!= ………………………..
Recursive Functions
• Since
• 5! = 5*4! = 5*4*3!= ………………………..
• Then we can use recursive functions
• Where n is multiplied by factorial n-1

• What is the terminating condition ?
• N reaches 1
double power(double x, int n)
{
if(n==0)
return 1.0;
return x*power(x, n-1);
}
Arrays
Arrays
• A collection of variables of the same type, stored
consecutively in the memory and referenced by a single name
• Single Dimensional Arrays
• Datatype varname[size]

• Size must be a constant , can’t be a variable and can’t be
changed at runtime.
• Example:
• int ar[5]
Allocates 5 integer addresses in the memory.

• Elements are accessed by indexing the array name, index are
zero based
• ar[0]  1st elelment
• ar[3]  4th element
Arrays
• Take care that C doesn’t check for out-of –boundary errors. It
is the programmer’s responsibility.
• For loops are closely related to arrays since it is used to
sequentially read/write array elements.

• Remember:
first element

the name of the array is the address of the
Write a program that fills an array with numbers
from 1 to 100, then print them to the screen.
int main()
{
int x[100];
int t;
for(t=0;t<100;t++)
{
x[t]=t+1;
}
for(t=0;t<100;t++)
{
printf(“%dn”, x*t+);
}
}
Write a program that let user input 5 employee
salaries and calculate sum of salaries.
int main()
{
float sum=0;
float salary[100];
int t;
for(t=0;t<5;t++)
{
printf(“Enter Salary: ”); scanf(“%f”, &salary*t+);
}
for(t=0;t<5;t++)
{
sum+=salary[t];
}
printf(“nSum of Salaries: %f”,sum);
return 0;
}
Array Initialization
• int ar[5]={1,2,3,4,5};
• int ar[]={1,2,3,4,5};
• int ar[5]={1,2,3};
 the rest of the elements are initialized to zero.
2D Array
• datatype varname[size1][size2]
• Example:
int ar[5][10];
 2D array of size 5 rows and 10 cols
• For 2D arrays we need to use nested for loops.
• Accessing a 2D array element through 2 indexes.
• ar[1][2] is elemetn in 2nd row, 3rd column
Write a program to fill a 3x4 array with numbers 112 and print them
int main()
{
int row,col,count=1,num[3][4];
for(row=0;row<3;row++)
{
for (col=0;col<4;col++)
{
num[row][col]=count++;
}
}
for(row=0;row<3;row++)
{
for (col=0;col<=4;col++)
{
print(“%dt”,num[row][col]);
}
}
return 0;
}
Write a program to fill a 3x4 array with numbers 112 and print them in reverse order
int main()
{
int row,col,count=1,num[3][4];
for(row=0;row<3;row++)
{
for (col=0;col<4;col++)
{
num[row][col]=count++;
}
}
for(row=2;row>=0;row--)
{
for (col=3;col>=0;col--)
{
print(“%dt”,num[row][col]);
}
}
return 0;
}
Write a program to fill a 3x4 array with numbers 112 and print them in col by col order
int main()
{
int row,col,count=1,num[3][4];
for(row=0;row<3;row++)
{
for (col=0;col<4;col++)
{
num[row][col]=count++;
}
}
for (col=0;col<4;col++)
{
for(row=0row<=3;row++)
{
print(“%dt”,num[row][col]);
}
}
return 0;
}
2D Array initialization
• int ar[3][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
• int ar[3][5]= {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
Passing arrays to functions
• We can’t pass the whole array values to a function, we just
pass the address of the first location.
• Examples
• void fun1(int ar[])
• int fun2(char carr[])
WHY?????
• void fun3(int ar[][4])  must give the second dimension.
What’s the output?
void fun1(int x[])
{
int t;
for(t=0;t<5;t++)
x[t]=t+1;
}
int main()
{
int x[5]={1,2}; int t;
for(t=0;t<5;t++)
printf("%dn", x[t]);
fun1(x);
for(t=0;t<5;t++)
printf("%dn", x[t]);
return 0;
}
Characters and
Strings
Characters in Memory
• Characters are stored in their ascii codes. Each key on the
keyboard has a representation in ascii codes.
A65, a97, ~126

• C stored characters in one byte.
• C divides keyboard keys into 2 categories
• Normal keys:
• When pressed only one byte is sent to the buffer.
• 0 -> 32 control characters
• 33 -> 127 printable characters

• Extended keys
• When pressed sends two bytes to the buffer, the first one as a
null(‘0’) or 0 ascii code.
What is the output?
int main()
{
char c;
c=getch();
if(!c){
printf("extended key");
c=getch();
printf("%d",c);
}
else printf("normal key %d",c);
return 0;
}
Write a program that prints the
characters from Ascii 60 to 80.
int main()
{
int i;
for(i=60; i<=80;i++)
{
printf(“%c  %dn”, I,I);
}
return 0;
}
Character Library - ctype.h
•
•
•
•
•
•
•
•
•

isalnum
isalph
isdigit
isspace
isprint
islower
isupper
toupper
tolower
Strings
• C doesn’t have a data type called strings
• To define a string , define an array of characters
• Example:
• char a[10]  defines a string of 9 characters and a terminating
null character
• Must always add an element for null
• char str*+=“hello”;
 reserves 5+1=6 bytes to save the array

• char str*+=,‘h’,’e’,’l’,’l’,’o’-;
incorrect initialization since no null character to terminate string,
causes unpredictable o/p

• char str*6+=,‘h’,’e’,’l’,’l’,’o’-;
adds a null automatically
printf and scanf
• To print a string, instead of character by character
• Use “%s” format specifier with printf()
• Use puts()

• To input a string, instead of character by character
• Use “%s” format specifier with scanf()
• Use gets();

• Remember: name of string is a pointer to first char element
string.h
•
•
•
•

strcpy
strcat
strlen
strcmp
Write a program input first and last
name to print the full name
int main()
{
char fname[10], lname[10], full[20];
scanf(“%s”,fname);
scanf(“%s”, lname);
strcpy(full,fname);
strcat(full,” “);
strcat(full,lname);
printf(“%s”,full);
return 0;
}
Assignments
• Assignment 1: Search for Fibonacci Numbers, write a function
to generate an array of them
Lab
• Write a program to calculate volume of 5 rooms, first save
width, breadth and height of each room.
• Write a function for the previous program to take the 2d array
describing the rooms and return the sum of volumes.
• Write a function to create a serial-number generator, where each
call to the function returns a number incremented by 23.
• Write a function to ask user for his name and input it character by
character into an array, then print it in uppercase as a string.
Bonus
• Write a program to print the following menu and navigate
through it using UP,DOWN arrows. ESC ends the program.
Enter prints the users choice. If Enter is pressed on Close, the
program ends too.
Open
Edit
Save
Close
Pointers
Pointers
• Is a variable carrying the address of another.
• Declaring a pointer, using * unary operator
int count=10;
int * int_pointer;
int_pointer=&count;
Pointers
int count=10;
int * int_pointer;
int_pointer=&count;
int x;
x=*int_pointer ;

• Remember
• * in declaration of variable denotes a pointer declaration
• * pointer_var in any statement denotes the value the pointer
points at
• & count denotes the address of count
What’s the output?
int main (void)
{
int count = 10, x;
int *int_pointer;
int_pointer = &count;
x = *int_pointer;
printf ("count = %d, x = %dn", count, x)

}
What’s the output?
int main ()
{
char c = 'Q';
char *char_pointer = &c;
printf ("%c %cn", c, *char_pointer);
c = '/';
printf ("%c %cn", c, *char_pointer);
*char_pointer = '(';
printf ("%c %cn", c, *char_pointer);
return 0;

}
Pointers and Arrays
int values[10]={1,2,3,4,5,6,7,8,9,10};
int *pv=NULL;
pv=values or
pv=&values[0];

• To assign a pointer to an array we declare a
pointer to the data-type of the array, then
assign it to the first element
What’s the output?
int arraySum (int array[], const int n)
{
int sum = 0, *ptr;
int * arrayEnd = array + n;
for ( ptr = array; ptr < arrayEnd; ++ptr )
sum += *ptr;
return sum;
}
int main ()
{
int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 };
printf ("The sum is %dn", arraySum (values, 10));
return 0;
}
Accessing Elements
• values[3]  *(valuesPtr+3)  to access value stored in 4th
location
• &value[2]  values+2  address of 3rd element.
• We can use either way as they are both equivalent
Operations on Pointers
• Add or subtract integer values from pointers.
• Compare two pointers to see if they are equal or not, or if one
pointer is less than or greater than another pointer.
• subtracting two pointers of the same type, the result is the
number of elements contained between the two pointers.
• Examples:
•
•
•
•

p1=&values[2];
p2=&values[7];
p1+4  &values[6] as an address to this element
p2-p1  5 as an integer
Write a function to count string
length using pointers
int stringLength (char *string)
{
char *cptr = string;
while ( *cptr ) ++cptr;
return cptr - string;
}
int main (void)
{
printf ("%d ", stringLength ("stringLength test"));
printf ("%d", stringLength (""));
return 0;
}
Note
• Arrays are passed to functions as addressed
(Call-by-address) always
int fun1(int ar[]) == int fun1(int * ar)

• For better performance,
• If we deal with arrays sequentially  use
pointers
• If we deal with arrays randomly  use Index.
Pointers and Functions
• Revisiting Call-by-address
• Pointers are passed to a function as arguments.
• The contents of the address can be accessed freely from
within the function.
Write a function to swap 2 numbers.
void swap(int x, int y);
int main()
{
int a=5, b=7;
swap(a,b);
printf(“a= %d and b= %d”,a,b);
return 0;
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}

?
Write a function to swap 2 numbers.
void swap(int *x, int *y);
int main()
{
int a=5, b=7;
swap(&a, b);
printf(“a= %d and b= %d”,a,b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Returning Pointers
• Never return a pointer to a local variable.
What’s the output?
void test (int *int_pointer)
{
*int_pointer = 100;
}
int main (void)
{
int i = 50, *p = &i;
printf ("Before the call to test i = %dn", i);
test (p);
printf ("After the call to test i = %dn", i);
return 0;
}
What do this program do?
char* match(char c, char *c);
int main()
{
char s[10], *p, ch;
gets(s); ch=getchar();
p=match(ch,s);
if(*p) printf(“%s”,p);
else printf(“No match
found”);
return 0;
}

char * match(char c , char*s)
{
while(c!=*s && *s)
s++;
return (s);
}
Array of Strings/Pointers

char *days[] =
{
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };
Pointers & Dynamic
Allocation
Dynamic Allocation
• A program can obtain memory while running.
• Memory allocated in the heap.
• Gives us the flexibility of allocating a variable amount of
memory in the runtime.
• stdlib.h
• void * malloc(numbytes)
• void free(void* )
Write a program to allocate an
integer.
int main()
{
int *pn=NULL;
pn=(int)malloc(sizeof(int));
if(!pn)
printf(“Out of memory”);
else
{
scanf(“%d”, pn);
printf(“%d”, *pn);
free(pn)
}
}
Note
• It is your responsibility to free any allocated
memory.
To allocate an array
int *pn;
pn=(int *)malloc(10*sizeof(int));

free(pn)
To allocate a variable length array of
names( variable length too)
char **names; int len;
int n =5; //number of names
names = (char **)malloc(n*sizeof(char*));
for(i-0; i<n;i++){
scanf(“%d”,&len);
names[i]= (char *)malloc(len*sizeof(char));
}

Pointer to pointer
Structure
Structure
• Is a group of variables under one name and is called an
aggregate data type.
• Structure Declaration:
• Must declare a template to be used to create structure variables.
• The declaration must be global so that all functions can use it.
struct struct_name
{
type var1;
type var2;
type var3;
} ;
Structure
• Example
struct addr
{
char street[10];
int streetNo;
char city[20];
} ;
Declaring a struct variable
• Declaration use keyword struct with name of structure
• struct addr addr1;
• addr1 is a variable, allocated space in the memory according to
data types defined in the struct addr declaraion

• Accessing elements inside structures using “.” dot notation.
• addr1.streetNo=3;
• strcpy(addr1.street,“New street”);
• strcpy(addr1.city,“Alex”);
Write a program to get your address
then print it on the screen
struct addr{
char street[40];
int streetNo;
};
int main()
{
struct addr myaddr;
printf(“Enter your address:n Street: ”);
scanf(“%s”,myaddr.street);
printf(“Street No: ”);
scanf(“%d”,&myaddr.streetNo);
printf(“The address entered is Street %s no. %d ”,
myaddr.street, myaddr.streetNo);
}
Arrays
• Declaring an array of 10 elements of struct addr
• struct addr arr[10];

• To access streetNo of element 3
• arr[2].streetNo=7
Functions
• Passing a structure as an argument to a function can be done by callby-value or call-by-address like a normal variable.
• Example:
void func1(struct addr x)
{
printf(“Address is : %d %s”, x.streetNo, x.street);
}
int main()
{
struct addr add;
add.streetNo=5;
strcpy(add.street,“My street”);
func1(add);
return 0;
}
Pointer to structure
• Declaring a pointer to structure
• struct addr * padd;

• To access elements, we use “->” arrow operator.
• padd->streetNo=6;

• Don’t forget that before using the pointer it must be assigned
an address of a structure, or dynamically allocated. NEVER

use unassigned pointers.
Example
struct date
{
int month;
int day;
int year;
};

int main()
{
struct date today, *datePtr;
datePtr=&today;
datePtr->month =10;
datePtr->day =2;
datePtr->year=2013;
printf(“Today is %d-%d-%d”, datePtr>day,datePtr->month,datePtr->year);
return 0;
}
Structures containing a pointer
struct mys
{
int *p1;
int * p2;
};
int i1=100, i2=200; struct mys s;
s.p1=&i1;
s.p2=&i2;
*s.p2=88;
printf ("i1 = %d, *s.p1 = %dn", i1, *pointers.p1);
printf ("i2 = %d, *s.p2 = %dn", i2, *pointers.p2);
Nested structures and arrays
• A structure can contain another structure (must be declared
before it) or array.
• Example:
struct addr{
char street[10];
int streetNo;
};
struct student{
char name[20];
int marks[5];
struct addr homeaddress;
};
Nested structures and arrays
• To access elements in a variable of type struct employee
struct student st1;
strcpy(st1.name,“Ahmed”);
st1.marks[3]=100;
st1.homeaddress.streetNo=20;
Assignments
• Assignment 1: How can we initialize Structures and Array of
structures?
• Assignment 2: What are pointers to functions
• Assignment 3: Read on linked lists on page 244. Write a
program to traverse a Linked List and Search for a value in it.
Lab
• Write a function trim4 that takes a string and truncates the
characters after the 4th and returns the new truncated string
without changing the original.
• Write a function that reverse a string using pointers.
• Create the following structures:
• date(int day, int month , int year),
• Student(int serial, char[] name, int marks)
• school(student* students, int numofStudents , char[] address, char
name[] )

• Write a function to fill data of a school.
• Write a function to print data of a school.
• Write a program to fill and print data of n schools (Bonus))
Bonus
• Add Highlighting to the previous Menu bonus
• Hint: Search for the following functions can be helpful
textattr(), textcolor(), textbackground()

More Related Content

What's hot

Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Eelco Visser
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit IIIManoj Patil
 
Cs6660 compiler design
Cs6660 compiler designCs6660 compiler design
Cs6660 compiler designhari2010
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 
Chapter One
Chapter OneChapter One
Chapter Onebolovv
 
Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)guest251d9a
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler ConstructionSarmad Ali
 
Lecture2 general structure of a compiler
Lecture2 general structure of a compilerLecture2 general structure of a compiler
Lecture2 general structure of a compilerMahesh Kumar Chelimilla
 
Error Detection & Recovery
Error Detection & RecoveryError Detection & Recovery
Error Detection & RecoveryAkhil Kaushik
 
Passes of compilers
Passes of compilersPasses of compilers
Passes of compilersVairavel C
 
Lecture 1 Compiler design , computation
Lecture 1 Compiler design , computation Lecture 1 Compiler design , computation
Lecture 1 Compiler design , computation Rebaz Najeeb
 

What's hot (20)

Compilers Design
Compilers DesignCompilers Design
Compilers Design
 
Compiler1
Compiler1Compiler1
Compiler1
 
Compiler
CompilerCompiler
Compiler
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?
 
Compiler unit 1
Compiler unit 1Compiler unit 1
Compiler unit 1
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
 
Cs6660 compiler design
Cs6660 compiler designCs6660 compiler design
Cs6660 compiler design
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Chapter One
Chapter OneChapter One
Chapter One
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Introduction to compilers
Introduction to compilersIntroduction to compilers
Introduction to compilers
 
Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
Lecture2 general structure of a compiler
Lecture2 general structure of a compilerLecture2 general structure of a compiler
Lecture2 general structure of a compiler
 
Error Detection & Recovery
Error Detection & RecoveryError Detection & Recovery
Error Detection & Recovery
 
Passes of compilers
Passes of compilersPasses of compilers
Passes of compilers
 
Lecture 1 Compiler design , computation
Lecture 1 Compiler design , computation Lecture 1 Compiler design , computation
Lecture 1 Compiler design , computation
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compiler
 
Lecture1 introduction compilers
Lecture1 introduction compilersLecture1 introduction compilers
Lecture1 introduction compilers
 

Viewers also liked

Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityAakash Singh
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
اینفوگرافی تبلیغات بنری
اینفوگرافی تبلیغات بنری اینفوگرافی تبلیغات بنری
اینفوگرافی تبلیغات بنری Anetwork
 
VSHMPR Fall Conference
VSHMPR Fall ConferenceVSHMPR Fall Conference
VSHMPR Fall ConferenceLee Aase
 
Check In Presentation 2016 David Pyman
Check In Presentation 2016 David PymanCheck In Presentation 2016 David Pyman
Check In Presentation 2016 David PymanDavid Pyman
 
Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”
Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”
Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”SiteGround España
 
Resilience and Hope: #ShareTheJourney with Congolese Refugees
Resilience and Hope: #ShareTheJourney with Congolese RefugeesResilience and Hope: #ShareTheJourney with Congolese Refugees
Resilience and Hope: #ShareTheJourney with Congolese RefugeesEpiscopal Migration Ministries
 
Personaje tecnológico
Personaje tecnológicoPersonaje tecnológico
Personaje tecnológicoALECOXSDB
 
World Economic Forum on the Middle East 2006
World Economic Forum on the Middle East 2006World Economic Forum on the Middle East 2006
World Economic Forum on the Middle East 2006WorldEconomicForumDavos
 
Remanso negro fuente de vida
Remanso negro fuente de vidaRemanso negro fuente de vida
Remanso negro fuente de vidabolzonella
 
Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...
Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...
Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...gretagreiss85
 
SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話
SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話
SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話SORACOM,INC
 
SearchLove London | Dave Sottimano, 'Using Data to Win Arguments'
SearchLove London | Dave Sottimano, 'Using Data to Win Arguments' SearchLove London | Dave Sottimano, 'Using Data to Win Arguments'
SearchLove London | Dave Sottimano, 'Using Data to Win Arguments' Distilled
 

Viewers also liked (19)

Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Type conversion
Type conversionType conversion
Type conversion
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
 
اینفوگرافی تبلیغات بنری
اینفوگرافی تبلیغات بنری اینفوگرافی تبلیغات بنری
اینفوگرافی تبلیغات بنری
 
VSHMPR Fall Conference
VSHMPR Fall ConferenceVSHMPR Fall Conference
VSHMPR Fall Conference
 
Check In Presentation 2016 David Pyman
Check In Presentation 2016 David PymanCheck In Presentation 2016 David Pyman
Check In Presentation 2016 David Pyman
 
Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”
Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”
Presentación Webinar “¿Por qué Yoast y no otro plugin SEO?”
 
Zaragoza turismo 235
Zaragoza turismo 235Zaragoza turismo 235
Zaragoza turismo 235
 
Resilience and Hope: #ShareTheJourney with Congolese Refugees
Resilience and Hope: #ShareTheJourney with Congolese RefugeesResilience and Hope: #ShareTheJourney with Congolese Refugees
Resilience and Hope: #ShareTheJourney with Congolese Refugees
 
Personaje tecnológico
Personaje tecnológicoPersonaje tecnológico
Personaje tecnológico
 
World Economic Forum on the Middle East 2006
World Economic Forum on the Middle East 2006World Economic Forum on the Middle East 2006
World Economic Forum on the Middle East 2006
 
Remanso negro fuente de vida
Remanso negro fuente de vidaRemanso negro fuente de vida
Remanso negro fuente de vida
 
Research2.0
Research2.0Research2.0
Research2.0
 
Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...
Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...
Uso di strumenti Web 2.0 per la realizzazione di applicazioni sostenibili in ...
 
SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話
SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話
SORACOM UG #2 | Mobile World Congressに行ってあんまりMobileじゃないものばかり見てきた話
 
SearchLove London | Dave Sottimano, 'Using Data to Win Arguments'
SearchLove London | Dave Sottimano, 'Using Data to Win Arguments' SearchLove London | Dave Sottimano, 'Using Data to Win Arguments'
SearchLove London | Dave Sottimano, 'Using Data to Win Arguments'
 

Similar to C for Engineers

Similar to C for Engineers (20)

Unit ii
Unit   iiUnit   ii
Unit ii
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
C language unit-1
C language unit-1C language unit-1
C language unit-1
 
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDYC LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
C programming
C programmingC programming
C programming
 
C language
C languageC language
C language
 
Embedded _c_
Embedded  _c_Embedded  _c_
Embedded _c_
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
Chapter 1: Introduction
Chapter 1: IntroductionChapter 1: Introduction
Chapter 1: Introduction
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Valuable Information on Lexical Analysis in Compiler Design
Valuable Information on Lexical Analysis in Compiler DesignValuable Information on Lexical Analysis in Compiler Design
Valuable Information on Lexical Analysis in Compiler Design
 
FPL - Part 1 (Sem - I 2013 )
FPL - Part 1  (Sem - I  2013 ) FPL - Part 1  (Sem - I  2013 )
FPL - Part 1 (Sem - I 2013 )
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 

More from Julie Iskander (20)

HTML 5
HTML 5HTML 5
HTML 5
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Design Pattern lecture 3
Design Pattern lecture 3Design Pattern lecture 3
Design Pattern lecture 3
 
Scriptaculous
ScriptaculousScriptaculous
Scriptaculous
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
Design Pattern lecture 4
Design Pattern lecture 4Design Pattern lecture 4
Design Pattern lecture 4
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2
 
Design Pattern lecture 1
Design Pattern lecture 1Design Pattern lecture 1
Design Pattern lecture 1
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAX
 
jQuery
jQueryjQuery
jQuery
 
ASP.NET Lecture 5
ASP.NET Lecture 5ASP.NET Lecture 5
ASP.NET Lecture 5
 
ASP.NET lecture 8
ASP.NET lecture 8ASP.NET lecture 8
ASP.NET lecture 8
 
ASP.NET Lecture 7
ASP.NET Lecture 7ASP.NET Lecture 7
ASP.NET Lecture 7
 
ASP.NET Lecture 6
ASP.NET Lecture 6ASP.NET Lecture 6
ASP.NET Lecture 6
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
ASP.NET Lecture 3
ASP.NET Lecture 3ASP.NET Lecture 3
ASP.NET Lecture 3
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
AJAX and JSON
AJAX and JSONAJAX and JSON
AJAX and JSON
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 

Recently uploaded

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Recently uploaded (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

C for Engineers

  • 1. C for Engineers Julie Iskander, MSc. Communication and Electronics
  • 2. Course Outlines • • • • • • Introduction to Programming C Program Data Types, Variable and Constants Control Statements and loops and functions Memory Management and Pointers Structures
  • 4. What is a Computer Program? • Computers are dumb machines. • A Computer Program is a set of instructions, written in a language the computer understands, to tell the computer what to do to solve a problem. • The approach or method used to solve a problem is called an algorithm • Example: • How to write a program to tell if a number is odd or even?
  • 5. Programming Language • Machine Language • Low-level languages • High level languages
  • 6. Compilers • To support a higher-level language, a special computer program must be used that translates the statements of the high-level language program into the particular instructions of the computer. • A compiler analyzes a program and then translates it into a form that is suitable for execution on your particular computer system. • Types of errors: • Syntax error  detected by compiler • Logical error  is not detected by compiler, but makes code give unpredicted results.
  • 7. Programming Methodologies • Linear Programming • Structural Programming • Object Oriented Programming
  • 9. Dennis Ritchie (1941-2011) • Designer and original developer of the C programming language. • A central figure in the development of Unix. • Was awarded the Turing Award in 1983, and the National Medal of Technology in 1999. • "Ritchie's influence rivals Jobs's; it's just less visible," James Grimmelman observed on Twitter. "His pointer has been cast to void *; his process has terminated with exit code 0."
  • 10. C Programming Language • C is a general-purpose programming language initially developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs. • Its design provides efficient mapping to typical machine instructions, thus substitutes assembly language, • Portable, as it is not difficult to write programs that can be run without change on a variety of hardware • Most of the Linux and UNIX operating systems are written in C.
  • 11. C is a “higher-level language,” yet it provides capabilities that enable the user to “get in close” with the hardware and deal with the computer on a much lower level. “PROGRAMMING IN C”, THIRD EDITION, STEPHEN G. KOCHAN
  • 12. C Compiler *.c compiler .obj linker .exe Compilers translate an entire file of code all at once, rather than line by line. Generate all error messages Creates an intermediate file, waiting to be linked to any external libraries needed, to create a final executable file Linker combines your object file with object files already found in the libraries.
  • 13.
  • 15. C Program PreProcessor Program Body #include <stdio.h> int main() { printf(“Hello C ”); return 0; }
  • 16. #include directive • Tells the compiler to insert another file at this location of your source code. • The new inserted code is compiled with the rest of the source code. • Also include header files (*.h). • A header file is a file that contains the function prototype of the functions defined in the library file before compilation, the compiler will add the header file contents to the source code. At compilation, the compiler can check function signatures against syntax errors.
  • 17. Program Body Entry Point of the program. A program must contain atleast on function, main() int main() { variable or constant declaration; statements; return 0; } All variables must be declared before any statement is executed
  • 18. C Comments • Not executable statement, documents the code • Ignored by compiler • Single line Comment // this is a single line comment • Multi – line Comment /* This is a longer comment That spans across multiple lines ……………………….. */
  • 19. Data types, Variables , Constants
  • 20. Data types • There are 5 fundamental data types 1. 2. 3. 4. 5. char (1 byte) int (2 bytes) float (4 bytes) double (8 bytes) Void • Size may differ from platform to another • Can add type modifier to the data types to alter its meaning (unsigned, signed, long, short) • Example • Signed char  0 to 255 • unsigned char  -127 to 127
  • 21. Variables • A place to store data, for further usage. • Declaring Variables: • datatype variable_name • datatype variable_list • Example: • int x; • char a,b,c,e; • C doesn’t initialize variables. • After declaring a variable, it can be used multiple times
  • 22. Variables Local Variables Global Variables • Declared inside a function • Available only for the function. • Ends with the function, closing brackets of the function • Declared out of any function • Available for all functions • Not recommended to use it extensively.
  • 23. Constants • A fixed value, that can’t be changed at any part of the program • There are two ways to define a constant value • As a macro, in the preprocessor using define • #define PI 3.14 • In a program body • const int pi=3.14; • Must be initialized when declared
  • 24. Statements • Are executable lines of code • Ends in ; • Can be a input statement, expression or operation or output statement
  • 25. I/O statements • Output function: display the results on the screen • printf() • printf(“string”,*,data+); • Example: printf(“Hello”); int x=3; printf(“x is %d”,x); • Format specifiers • • • • %d integer %f float %c char %lf double • putchar(): puts a character on the screen. • Example: • putchar(‘a’) ; or putchar(23);
  • 26. I/O statements • Input function: wait for user to enter values and save it. • scanf(“format-specifier”, address -of-var): Wait for user to input, must specify the data type of the input (format specifier) and the address to store value in • getchar() Reads one character only from keyboard and wait for carriage return, character is printed to screen • getch() (only bc) Reads one character only from keyboard without waiting for carriage return, character is not printed to screen • getche() (only bc) Reads one character only from keyboard without waiting for carriage return, character is printed to screen
  • 30. C Memory Managment Stack Heap Uninitialized data segment Global and static Variables Section (Initialized Data Segment) Executable Code Section (Code Segment)
  • 31. Assignments • Assignment 1: The history of programming languages. • Assignment 2: Interpreter Versus Compiler • Assignment 3: What’s the output of the following: int a=25, b=3; printf("%d", a/b*b); Why?
  • 32. Lab • Install Borland C 3.1 or Cygwin • Write hello.c to print Hello world • Write a program to print the following with the same format *********** **Hello all** *********** with one printf statement. Use escape sequences like n,t,…..etc. • Fix errors in error1.c and error2.c. • Write a program to ask user to enter the number of the day in a year and the program will output the day and month. Assume all month has 30 days. • Try writing a function for the previous assignment • Try casting and operator precedence
  • 35. • Write a program to specify if a number is odd or even int main() { int num; printf(“Enter a number: ”); scanf(“%d”, &num); if(num%2) { printf(“Odd”); } else { printf(“Even”); } return 0; }
  • 37. • Write a program to print grade of students according to his marks int main() { int mark; printf(“Enter your mark: ”); scanf(“%d”, &mark); if(mark>=90) printf(“A”); else if(mark>=80) printf(“B”); else if(mark>=70) printf(“C”); else printf(“Failed”); return 0; }
  • 39. Write a program to print marks range of students according to his grade int main() { char mark; printf(“Enter your mark: ”); scanf("%c",&mark); switch (mark) { case ‘A’:, printf(“Marks between 100 and 90”); break; } case ‘B’: , printf(“Marks between 90 and 80”); break; } case ‘C’: { printf(“Marks between 80 and 70”); break; } default: { printf(“less than 70”); } } return 0; }
  • 40. break • What if we forget a break in any case? Fall through • All sequential cases till the first break or end of cases will be evaluated
  • 42. Looping • Is repeating a block of code for a specific times or until a condition is satisfied. • Loops can be terminated using break statement, or an iteration skipped using continue statement.
  • 43. for loop for( initialization ; condition ; increment ) { statements to be repeated; } • Initialization is a statement executed once at the start of the loop. • Condition is evaluated before every iteration, to decide to go on or quit the loop, must evaluate to true/false • Increment is a statement executed at the end of each iteration • Used for repeating code a specific number of times
  • 44. • Write a program to print numbers from 1 to 100 int main() { int i; for(i=1; i<=100 ;i++) { printf("%dn",i); } return 0; }
  • 45. • What’s the output? int main() { int i; for(i=1; i<=100 ;i++) { if(i==10) continue; printf("%dn",i); } return 0; }
  • 46. • What’s the output? int main() { int i; for(i=1; i<=100 ;i++) { printf("%dn",i); if(i==10) break; } return 0; }
  • 47. • What’s the output? int main() { int i; for(i=1; i<=100 ;i++) { if(i==10) break; printf("%dn",i); } return 0; }
  • 48. • What’s the output? int main() { int i=0; for(; ;) { i++; printf("%dn",i); } return 0; }
  • 49. • Write a program to take a character and print it till z is entered? int main() { char c; for(c=0; c!='z';) { printf("Enter a character"); c=getchar(); getchar(); } return 0; } Why do we need to add another getchar()?
  • 50. • Write a program to calculate the average of marks of 10 students int main() { int i, mark ; int sum=0, avg; for(i=0; i<10 ;i++) { printf("Enter a student mark : "); scanf(“%d”, &mark); sum+=mark; } avg=sum/10; printf(“Average of student marks is %d”,avg); return 0; }
  • 51. Nested for loops What’s the output? int main (void) { int n, number, triangularNumber, counter; for ( counter = 1; counter <= 5; ++counter ) { printf ("What triangular number do you want? "); scanf ("%i", &number); triangularNumber = 0; for ( n = 1; n <= number; ++n ) triangularNumber += n; printf ("Triangular number %i is %inn", number, triangularNumber); } return 0; }
  • 52. while loop while(condition) { statements to be repeated; } • Used for repeating a block of code until a condition is met, the condition is tested before executing the block of code. • The block of code can never be executed
  • 53. int main() { int n,x,i=1,multi=1; printf(“Enter x:”); scanf(“%d”,&x); printf(“Enter n:”); scanf(“%d”,&n); while(i<=n) { multi*=x; i++; } printf(“y is %d”,multi); return 0; }
  • 54. do…….while loop do { statements to be repeated; } while(condition); • Used for repeating a block of code until a condition is met, the condition is tested after executing the block of code. • The block of code is executed at least once
  • 55. What is the error in this code? int main() { int n,x,i=1,multi=1; printf(“Enter x:”); scanf(“%d”,&x); printf(“Enter n:”); scanf(“%d”,&n); do{ multi*=x; i++; } while(i<=n); printf(“y is %d”,multi); return 0; }
  • 57. Functions • Is a block of code, that does a specific task. • Each program has atleast one function , main • Functions reduce duplicate code and make maintenance and modification easier and quicker • Any function has: • • • • Function name Return type List of input arguments body
  • 58. Functions • Function definition Return_type fun_name(list of args) { function body return statement } • A function can be defined before the main. • If defined after main, add a signature before the main. Used by compiler to check for syntax errors. • The return statement terminates the function and returns control to the calling function, is used to return a value
  • 59. Write a function to print a message #include <stdio.h> void sayhi(void); int main() { int a,b,y; sayhi(); } void sayhi(void); { printf(‘hi from function’); }
  • 60. Write a function to add 2 numbers #include <stdio.h> int add(int x, int y); int main() { int a,b,y; printf(“enter 2 numbers”); scanf(“%d”, &a); scanf(“%d”, &b); y=add(a,b); printf(“the sum is %d”,y) } int add(int x, int y) { int z; z=x+y; return z; } What happens in the memory during execution?
  • 61. Passing values to a function • Call by value • Where the whole data type is sent to the function and stored as a local variable to the function, a copy is made. • Changes done in the function as no effect on the original variables of the calling function • Call by address • Only the address of the argument is sent and stored with the function • Changes in the function affects the original variable in the calling function as it is referenced by its address • The calling and called functions access the same memory address
  • 62. Call by address • Both references the same memory location. Calling function x Called function Address of x
  • 63. Call by value • Each has it’s own version of the argument. Calling function x Called function x
  • 64. Assignments • Assignment 1: What is a conditional operator or ? Operator ? • Assignment 2: What are the pros and cons of using call-byvalue and call-by-address?
  • 65. Lab • Fix the errors in error1.c and error2.c • Write a function to calculate the factorial of n, use this function in main. • Write a function to reverse the digits in a given number, use this function in main. • Write a function that draws a MagicBox table, given its dimension, use function gotoxy to e able to draw it on the screen. • Write a program that inputs 5 numbers then prints out the min and max.
  • 66. Magic Box 6 1 8 7 5 3 2 9 4 • The size must be odd eg. 3x3, 5x5, 7x7, ……………. • Number 1 is put in row= 1 and col = (size+1)/2 • Numbers from 2 till size*size are put acc. to the following rule • If(number-1)%size ==nonzero • row-1 and col-1 • Or else • row+1
  • 68. Scope Rules • All functions are global , no nested functions in C • A function’s code is private to the function, can’t be accessed by other functions • Variables declared inside a block of code, is local to that block. They’re destroyed at the end of the block of code. • The input arguments of a function are local variables to it, declared in the definition of the function. void func1() { int x; x=10; } void func2() { int x; x=-1999; } • The variable x is declared twice, with no relation to each other. Each one is stored in a separate memory location and func1 can’t access the x in func2.
  • 69. Scope Rules • Global variables are declared out of all functions and can be accessed by all.
  • 70. What is the output? int count; int main() { count=100; printf("In main, count is %dn", count); func1(); printf("After func1 call in main count is %dn", count); } void func1() { printf("In func1, count is %dn", count); func2(); printf("In func1 after func2 call, count is %dn", count); } void func2() { int count=2; printf("In func2, count is %dn", count); }
  • 71. Static Variables • Are permanent variables within their own functions or file. • Not accessible to functions outside their function. • Maintain their values between function calls.
  • 72. What is the output? int main() { printf(“series is %d ", series()); printf(“series is %d", series()); printf(“series is %d", series()); } int series() { int num=0; num=num+23; return num; }
  • 73. What is the output now? int main() { printf(“series is %d", series()); printf(“series is %d", series()); printf(“series is %d", series()); } int series() { static int num=0; num=num+23; return num; }
  • 75. Recursive Functions • A function that calls itself. • Must contain a condition, to ensure a finite execution. • Example: factorial function • 5! = 5*4*3*2*1 • Using for loop int t=5, ans=1; for(; t>=1;t--) { ans*=t; } • 5! = 5*4! = 5*4*3!= ………………………..
  • 76. Recursive Functions • Since • 5! = 5*4! = 5*4*3!= ……………………….. • Then we can use recursive functions • Where n is multiplied by factorial n-1 • What is the terminating condition ? • N reaches 1
  • 77. double power(double x, int n) { if(n==0) return 1.0; return x*power(x, n-1); }
  • 79. Arrays • A collection of variables of the same type, stored consecutively in the memory and referenced by a single name • Single Dimensional Arrays • Datatype varname[size] • Size must be a constant , can’t be a variable and can’t be changed at runtime. • Example: • int ar[5] Allocates 5 integer addresses in the memory. • Elements are accessed by indexing the array name, index are zero based • ar[0]  1st elelment • ar[3]  4th element
  • 80. Arrays • Take care that C doesn’t check for out-of –boundary errors. It is the programmer’s responsibility. • For loops are closely related to arrays since it is used to sequentially read/write array elements. • Remember: first element the name of the array is the address of the
  • 81. Write a program that fills an array with numbers from 1 to 100, then print them to the screen. int main() { int x[100]; int t; for(t=0;t<100;t++) { x[t]=t+1; } for(t=0;t<100;t++) { printf(“%dn”, x*t+); } }
  • 82. Write a program that let user input 5 employee salaries and calculate sum of salaries. int main() { float sum=0; float salary[100]; int t; for(t=0;t<5;t++) { printf(“Enter Salary: ”); scanf(“%f”, &salary*t+); } for(t=0;t<5;t++) { sum+=salary[t]; } printf(“nSum of Salaries: %f”,sum); return 0; }
  • 83. Array Initialization • int ar[5]={1,2,3,4,5}; • int ar[]={1,2,3,4,5}; • int ar[5]={1,2,3};  the rest of the elements are initialized to zero.
  • 84. 2D Array • datatype varname[size1][size2] • Example: int ar[5][10];  2D array of size 5 rows and 10 cols • For 2D arrays we need to use nested for loops. • Accessing a 2D array element through 2 indexes. • ar[1][2] is elemetn in 2nd row, 3rd column
  • 85. Write a program to fill a 3x4 array with numbers 112 and print them int main() { int row,col,count=1,num[3][4]; for(row=0;row<3;row++) { for (col=0;col<4;col++) { num[row][col]=count++; } } for(row=0;row<3;row++) { for (col=0;col<=4;col++) { print(“%dt”,num[row][col]); } } return 0; }
  • 86. Write a program to fill a 3x4 array with numbers 112 and print them in reverse order int main() { int row,col,count=1,num[3][4]; for(row=0;row<3;row++) { for (col=0;col<4;col++) { num[row][col]=count++; } } for(row=2;row>=0;row--) { for (col=3;col>=0;col--) { print(“%dt”,num[row][col]); } } return 0; }
  • 87. Write a program to fill a 3x4 array with numbers 112 and print them in col by col order int main() { int row,col,count=1,num[3][4]; for(row=0;row<3;row++) { for (col=0;col<4;col++) { num[row][col]=count++; } } for (col=0;col<4;col++) { for(row=0row<=3;row++) { print(“%dt”,num[row][col]); } } return 0; }
  • 88. 2D Array initialization • int ar[3][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; • int ar[3][5]= {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
  • 89. Passing arrays to functions • We can’t pass the whole array values to a function, we just pass the address of the first location. • Examples • void fun1(int ar[]) • int fun2(char carr[]) WHY????? • void fun3(int ar[][4])  must give the second dimension.
  • 90. What’s the output? void fun1(int x[]) { int t; for(t=0;t<5;t++) x[t]=t+1; } int main() { int x[5]={1,2}; int t; for(t=0;t<5;t++) printf("%dn", x[t]); fun1(x); for(t=0;t<5;t++) printf("%dn", x[t]); return 0; }
  • 92. Characters in Memory • Characters are stored in their ascii codes. Each key on the keyboard has a representation in ascii codes. A65, a97, ~126 • C stored characters in one byte. • C divides keyboard keys into 2 categories • Normal keys: • When pressed only one byte is sent to the buffer. • 0 -> 32 control characters • 33 -> 127 printable characters • Extended keys • When pressed sends two bytes to the buffer, the first one as a null(‘0’) or 0 ascii code.
  • 93. What is the output? int main() { char c; c=getch(); if(!c){ printf("extended key"); c=getch(); printf("%d",c); } else printf("normal key %d",c); return 0; }
  • 94. Write a program that prints the characters from Ascii 60 to 80. int main() { int i; for(i=60; i<=80;i++) { printf(“%c  %dn”, I,I); } return 0; }
  • 95. Character Library - ctype.h • • • • • • • • • isalnum isalph isdigit isspace isprint islower isupper toupper tolower
  • 96. Strings • C doesn’t have a data type called strings • To define a string , define an array of characters • Example: • char a[10]  defines a string of 9 characters and a terminating null character • Must always add an element for null • char str*+=“hello”;  reserves 5+1=6 bytes to save the array • char str*+=,‘h’,’e’,’l’,’l’,’o’-; incorrect initialization since no null character to terminate string, causes unpredictable o/p • char str*6+=,‘h’,’e’,’l’,’l’,’o’-; adds a null automatically
  • 97. printf and scanf • To print a string, instead of character by character • Use “%s” format specifier with printf() • Use puts() • To input a string, instead of character by character • Use “%s” format specifier with scanf() • Use gets(); • Remember: name of string is a pointer to first char element
  • 99. Write a program input first and last name to print the full name int main() { char fname[10], lname[10], full[20]; scanf(“%s”,fname); scanf(“%s”, lname); strcpy(full,fname); strcat(full,” “); strcat(full,lname); printf(“%s”,full); return 0; }
  • 100. Assignments • Assignment 1: Search for Fibonacci Numbers, write a function to generate an array of them
  • 101. Lab • Write a program to calculate volume of 5 rooms, first save width, breadth and height of each room. • Write a function for the previous program to take the 2d array describing the rooms and return the sum of volumes. • Write a function to create a serial-number generator, where each call to the function returns a number incremented by 23. • Write a function to ask user for his name and input it character by character into an array, then print it in uppercase as a string.
  • 102. Bonus • Write a program to print the following menu and navigate through it using UP,DOWN arrows. ESC ends the program. Enter prints the users choice. If Enter is pressed on Close, the program ends too. Open Edit Save Close
  • 104. Pointers • Is a variable carrying the address of another. • Declaring a pointer, using * unary operator int count=10; int * int_pointer; int_pointer=&count;
  • 105. Pointers int count=10; int * int_pointer; int_pointer=&count; int x; x=*int_pointer ; • Remember • * in declaration of variable denotes a pointer declaration • * pointer_var in any statement denotes the value the pointer points at • & count denotes the address of count
  • 106. What’s the output? int main (void) { int count = 10, x; int *int_pointer; int_pointer = &count; x = *int_pointer; printf ("count = %d, x = %dn", count, x) }
  • 107. What’s the output? int main () { char c = 'Q'; char *char_pointer = &c; printf ("%c %cn", c, *char_pointer); c = '/'; printf ("%c %cn", c, *char_pointer); *char_pointer = '('; printf ("%c %cn", c, *char_pointer); return 0; }
  • 108.
  • 109.
  • 110. Pointers and Arrays int values[10]={1,2,3,4,5,6,7,8,9,10}; int *pv=NULL; pv=values or pv=&values[0]; • To assign a pointer to an array we declare a pointer to the data-type of the array, then assign it to the first element
  • 111. What’s the output? int arraySum (int array[], const int n) { int sum = 0, *ptr; int * arrayEnd = array + n; for ( ptr = array; ptr < arrayEnd; ++ptr ) sum += *ptr; return sum; } int main () { int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 }; printf ("The sum is %dn", arraySum (values, 10)); return 0; }
  • 112. Accessing Elements • values[3]  *(valuesPtr+3)  to access value stored in 4th location • &value[2]  values+2  address of 3rd element. • We can use either way as they are both equivalent
  • 113. Operations on Pointers • Add or subtract integer values from pointers. • Compare two pointers to see if they are equal or not, or if one pointer is less than or greater than another pointer. • subtracting two pointers of the same type, the result is the number of elements contained between the two pointers. • Examples: • • • • p1=&values[2]; p2=&values[7]; p1+4  &values[6] as an address to this element p2-p1  5 as an integer
  • 114. Write a function to count string length using pointers int stringLength (char *string) { char *cptr = string; while ( *cptr ) ++cptr; return cptr - string; } int main (void) { printf ("%d ", stringLength ("stringLength test")); printf ("%d", stringLength ("")); return 0; }
  • 115. Note • Arrays are passed to functions as addressed (Call-by-address) always int fun1(int ar[]) == int fun1(int * ar) • For better performance, • If we deal with arrays sequentially  use pointers • If we deal with arrays randomly  use Index.
  • 116. Pointers and Functions • Revisiting Call-by-address • Pointers are passed to a function as arguments. • The contents of the address can be accessed freely from within the function.
  • 117. Write a function to swap 2 numbers. void swap(int x, int y); int main() { int a=5, b=7; swap(a,b); printf(“a= %d and b= %d”,a,b); return 0; } void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } ?
  • 118. Write a function to swap 2 numbers. void swap(int *x, int *y); int main() { int a=5, b=7; swap(&a, b); printf(“a= %d and b= %d”,a,b); return 0; } void swap(int *x, int *y) { int temp; temp=*x; *x=*y; *y=temp; }
  • 119. Returning Pointers • Never return a pointer to a local variable.
  • 120. What’s the output? void test (int *int_pointer) { *int_pointer = 100; } int main (void) { int i = 50, *p = &i; printf ("Before the call to test i = %dn", i); test (p); printf ("After the call to test i = %dn", i); return 0; }
  • 121. What do this program do? char* match(char c, char *c); int main() { char s[10], *p, ch; gets(s); ch=getchar(); p=match(ch,s); if(*p) printf(“%s”,p); else printf(“No match found”); return 0; } char * match(char c , char*s) { while(c!=*s && *s) s++; return (s); }
  • 122. Array of Strings/Pointers char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  • 124. Dynamic Allocation • A program can obtain memory while running. • Memory allocated in the heap. • Gives us the flexibility of allocating a variable amount of memory in the runtime. • stdlib.h • void * malloc(numbytes) • void free(void* )
  • 125. Write a program to allocate an integer. int main() { int *pn=NULL; pn=(int)malloc(sizeof(int)); if(!pn) printf(“Out of memory”); else { scanf(“%d”, pn); printf(“%d”, *pn); free(pn) } }
  • 126. Note • It is your responsibility to free any allocated memory.
  • 127. To allocate an array int *pn; pn=(int *)malloc(10*sizeof(int)); free(pn)
  • 128. To allocate a variable length array of names( variable length too) char **names; int len; int n =5; //number of names names = (char **)malloc(n*sizeof(char*)); for(i-0; i<n;i++){ scanf(“%d”,&len); names[i]= (char *)malloc(len*sizeof(char)); } Pointer to pointer
  • 130. Structure • Is a group of variables under one name and is called an aggregate data type. • Structure Declaration: • Must declare a template to be used to create structure variables. • The declaration must be global so that all functions can use it. struct struct_name { type var1; type var2; type var3; } ;
  • 131. Structure • Example struct addr { char street[10]; int streetNo; char city[20]; } ;
  • 132. Declaring a struct variable • Declaration use keyword struct with name of structure • struct addr addr1; • addr1 is a variable, allocated space in the memory according to data types defined in the struct addr declaraion • Accessing elements inside structures using “.” dot notation. • addr1.streetNo=3; • strcpy(addr1.street,“New street”); • strcpy(addr1.city,“Alex”);
  • 133. Write a program to get your address then print it on the screen struct addr{ char street[40]; int streetNo; }; int main() { struct addr myaddr; printf(“Enter your address:n Street: ”); scanf(“%s”,myaddr.street); printf(“Street No: ”); scanf(“%d”,&myaddr.streetNo); printf(“The address entered is Street %s no. %d ”, myaddr.street, myaddr.streetNo); }
  • 134. Arrays • Declaring an array of 10 elements of struct addr • struct addr arr[10]; • To access streetNo of element 3 • arr[2].streetNo=7
  • 135. Functions • Passing a structure as an argument to a function can be done by callby-value or call-by-address like a normal variable. • Example: void func1(struct addr x) { printf(“Address is : %d %s”, x.streetNo, x.street); } int main() { struct addr add; add.streetNo=5; strcpy(add.street,“My street”); func1(add); return 0; }
  • 136. Pointer to structure • Declaring a pointer to structure • struct addr * padd; • To access elements, we use “->” arrow operator. • padd->streetNo=6; • Don’t forget that before using the pointer it must be assigned an address of a structure, or dynamically allocated. NEVER use unassigned pointers.
  • 137. Example struct date { int month; int day; int year; }; int main() { struct date today, *datePtr; datePtr=&today; datePtr->month =10; datePtr->day =2; datePtr->year=2013; printf(“Today is %d-%d-%d”, datePtr>day,datePtr->month,datePtr->year); return 0; }
  • 138.
  • 139. Structures containing a pointer struct mys { int *p1; int * p2; }; int i1=100, i2=200; struct mys s; s.p1=&i1; s.p2=&i2; *s.p2=88; printf ("i1 = %d, *s.p1 = %dn", i1, *pointers.p1); printf ("i2 = %d, *s.p2 = %dn", i2, *pointers.p2);
  • 140. Nested structures and arrays • A structure can contain another structure (must be declared before it) or array. • Example: struct addr{ char street[10]; int streetNo; }; struct student{ char name[20]; int marks[5]; struct addr homeaddress; };
  • 141. Nested structures and arrays • To access elements in a variable of type struct employee struct student st1; strcpy(st1.name,“Ahmed”); st1.marks[3]=100; st1.homeaddress.streetNo=20;
  • 142. Assignments • Assignment 1: How can we initialize Structures and Array of structures? • Assignment 2: What are pointers to functions • Assignment 3: Read on linked lists on page 244. Write a program to traverse a Linked List and Search for a value in it.
  • 143. Lab • Write a function trim4 that takes a string and truncates the characters after the 4th and returns the new truncated string without changing the original. • Write a function that reverse a string using pointers. • Create the following structures: • date(int day, int month , int year), • Student(int serial, char[] name, int marks) • school(student* students, int numofStudents , char[] address, char name[] ) • Write a function to fill data of a school. • Write a function to print data of a school. • Write a program to fill and print data of n schools (Bonus))
  • 144. Bonus • Add Highlighting to the previous Menu bonus • Hint: Search for the following functions can be helpful textattr(), textcolor(), textbackground()

Editor's Notes

  1. Assembly is hardware dependent as it is linked to a specific CPU.
  2. James Grimmelman , a Professor of Law at the University of Maryland, direct the Intellectual Property Program, and a Visiting Professor at the University of Maryland Institute for Advanced Computer Studies.
  3. PreProcessorInstructions to the compiler (Directives). #include, #define, #endif ,#ifdef, #elif
  4. Post and Pre increment
  5. Integer operation and precision loss
  6. Code Segment contains executable instructions. May be placed below the heap or stack in order to prevent heaps and stack overflows from overwriting it. It is usuallysharable so that only a single copy needs to be in memory for frequently executed programs, such as text editors, the C compiler, the shells, and so on. It is often read-only, to prevent a program from accidentally modifying its instructions.Initialized data segmentis a portion of virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer. It is not read-only, since the values of the variables can be altered at run time.This segment can be further classified into initialized read-only (const) area and initialized read-write area.Uninitialized data segment, often called the “bss” segment, named after an ancient assembler operator that stood for “block started by symbol.” Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executinguninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code.For instance a variable declared static inti; would be contained in the BSS segment.For instance a global variable declared int j; would be contained in the BSS segment.Stack hold return addresses of function calls, arguments to functions and local variables, also save the current state of the CPU.The stack area traditionally adjoined the heap area and grew the opposite direction; when the stack pointer met the heap pointer, free memory was exhausted. The stack area contains the program stack, a LIFO structure, typically located in the higher parts of memory. A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed” onto the stack. The set of values pushed for one function call is termed a “stack frame”; A stack frame consists at minimum of a return address.Each time a function is called, the address of where to return to and certain information about the caller’s environment, such as some of the machine registers, are saved on the stack. The newly called function then allocates room on the stack for its automatic and temporary variables. This is how recursive functions in C can work. Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t interfere with the variables from another instance of the function.Heap used for dynamic allocation, must be freed manually or when program exits.The heap area begins at the end of the BSS segment and grows to larger addresses from there. The Heap area is shared by all shared libraries and dynamically loaded modules in a process.
  7. How to make the quation correct without changing data type?
  8. Only test equalityWorks on int, long and char only
  9. #include&lt;stdio.h&gt;#include&lt;conio.h&gt;int fact(intnum);int main(){intsum,l;printf(&quot;enter the number&quot;);scanf(&quot;%d&quot;,&amp;sum);l=fact(sum);printf(&quot;%d&quot;,l);getch(); return 0;}int fact(intnum){int res=1;while(num!=0){res=res*num;num --;}return res;}
  10. How to make the quation correct without changing data type?
  11. In C language, 2D array is just an array of arrays. Because of that, you should pass the function a pointer to the first sub-array in the 2D array. 
  12. How to make the quation correct without changing data type?
  13. The sum is 21
  14. How to make the quation correct without changing data type?