Carnegie Mellon
Intro to C
Computer Systems Organization
1
Intro to C Programming
Introduction
A Simple C Program: Printing a Line of Text
Another Simple C Program: Adding Two Integers
Memory Concepts
Arithmetic in C
Decision Making: Equality and Relational Operators
Pointers
Reading from Command Line
Arrays
Strings
Structure
Dynamic Memory Allocation
2
Introduction
C programming language
• Widely used language
• Strengths: high speed and system programming
3
Comparing C and C++
Similarities
• Both have similar syntax
• for-loops, while-loops, if-else, function declaration, arithmetic …
• C++ is a superset of C
• C++ extends C
• Most C codes are also C++ codes
4
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
5
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
6
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
• Function and operator overloading What is function overloading?
int foo(int input)
{
// Code
}
int foo(string input)
{
// Code
}
7
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
• Function and operator overloading
• Namespaces
// first name space namespace
namespace first_space
{
int foo(string input);
// …
}
// second name space namespace
namespace second_space
{
int foo(string input);
// …
}
8
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
• Function and operator overloading
• Namespaces
• New and delete operators (use malloc() and free() instead)
9
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
• Function and operator overloading
• Namespaces
• New and delete operators (use malloc() and free() instead)
• Template classes and function
A function with
a generic type T
template<class T> T GetMax (T a, T b)
{
T result;
result = (a > b)? a : b;
return result;
}
10
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
• Function and operator overloading
• Namespaces
• New and delete operators (use malloc() and free() instead)
• Template classes and function
• Standard template library (STL)
11
Comparing C and C++
Differences
C does not support the following C++ language features
• Object oriented programming (classes …)
• C++ exception handling (try/catch)
• Function and operator overloading
• Namespaces
• New and delete operators (use malloc() and free() instead)
• Template classes and function
• Standard template library (STL)
• Reference types (e.g., int& x)
void swap(int& x, int& y) void swap(int* x, int* y)
{ {
int z = x; int z = *x;
x = y; *x = *y;
y = z; *y = z;
} }
… …
swap(x, y); swap(&x, &y);
C++ only C and C++
12
A Simple C Program: Printing a Line of Text
1 /* This is a comment */ Comments
2
3 #include <stdio.h>
4
5 int main()
Preprocessor
6 { directive
7 printf( "Welcome to C!\n" );
8
9 return 0;
10 }
Welcome to C!
Comments
◦ Text surrounded by /* and */ is ignored by computer
◦ Used to describe program
#include <stdio.h>
◦ Preprocessor directive
◦ Tells computer to load contents of a certain file
◦ <stdio.h> allows standard input/output operations
13
Compiler Steps
Preprocessor
Macro subs tu on
Stripping of comments
Expansion of included les
14
ti
ti
fi
A Simple C Program: Printing a Line of Text
1 /* This is a comment */
2
3 #include <stdio.h> main function
4
5 int main()
6 {
7 printf( "Welcome to C!\n” );
8
9 return 0;
10 }
Welcome to C!
int main()
◦ C programs contain one or more functions, exactly one
of which must be main
◦ int means that main "returns" an integer value
◦ Braces ({ and }) indicate a block
◦ The bodies of all functions must be contained in braces
15
General Form of Declaring a Function
ReturnType Name (Type Name, Type Name, Type Name)
{
16
A Simple C Program: Printing a Line of Text
1 /* This is a comment */
2
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n” );
8
9 return 0;
10 }
Welcome to C!
◦ Print a string Escape sequences i
◦ “\n” means start a new line \a alert (bell) character
\n newline
\t horizontal tab
\\ backslash
\′ single quote
\" double quote
17
s
A Simple C Program: Printing a Line of Text
1 /* This is a comment */
2
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n” );
8
9 return 0;
10 }
Welcome to C!
◦ Instructs computer to perform an action
◦ Specifically, prints the string of characters within quotes (“ ”)
◦ Entire line called a statement
◦ All statements must end with a semicolon (;)
18
A Simple C Program: Printing a Line of Text
1 /* This is a comment */
2
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n” );
8
9 return 0;
10 }
Welcome to C!
return 0;
◦ A way to exit a function
◦ return 0, in this case, means that the program terminated normally
19
Another Simple C Program: Adding Two Integers
1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read and integer */
12 sum = integer1 + integer2; /* assignment of sum
*/
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
Enter first integer
45
Enter second integer
72
Sum is 117
20
Another Simple C Program: Adding Two Integers
1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read and integer */
12 sum = integer1 + integer2; /* assignment of sum
*/
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
21
Another Simple C Program: Adding Two Integers
6 int integer1, integer2, sum; /* declaration */
◦ Declaration of variables
◦ Variables: locations in memory where a value can be stored
◦ int means the variables can hold integers (-1, 3, 0, 47)
◦ Variable names (identifiers)
◦ integer1, integer2, sum
◦ Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ )
◦ Case sensitive
◦ Declarations appear before executable statements
◦ If an executable statement references and undeclared variable it will produce a syntax
(compiler) error
22
Another Simple C Program: Adding Two Integers
1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read and integer */
12 sum = integer1 + integer2; /* assignment of sum
*/
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
23
Another Simple C Program: Adding Two Integers
9 scanf( "%d", &integer1 ); /* read an integer */
◦ Reads a value from the user
◦ scanf uses standard input (usually keyboard)
◦ scanf has two arguments
◦ ”%d”
◦ a string that specifies the format of the input (e.g., its type)
◦ %d indicates that data should be a decimal signed integer
◦ %u indicates that data should be an unsigned integer
◦ %f indicates that data should be a floating-point
◦ &integer1
◦ location in memory to store the read value
◦ & indicates passing integer1 by reference to the scanf() function
◦ & is confusing in the beginning – for now, just remember to include it with the variable
name in scanf statements
◦ When executing the program the user responds to the scanf statement by
typing in a number, then pressing the enter (return) key
24
Another Simple C Program: Adding Two Integers
1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read and integer */
12 sum = integer1 + integer2; /* assignment of sum
*/
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
25
Another Simple C Program: Adding Two Integers
13 printf( "Sum is %d\n", sum ); /* print sum */
◦ Similar to scanf
◦ %d means decimal integer will be printed
◦ sum specifies what integer will be printed
printf( “1st number is %d, while 2nd is %d\n”, 51, 23 );
1st number is 51, while 2nd is 23
26
Memory Concepts
Variables
◦ Variable names correspond to locations in the computer's memory
◦ Every variable has a name, a type, a size and a value
◦ Whenever a new value is placed into a variable (through scanf, for
example), it replaces (and destroys) the previous value
◦ Reading variables from memory does not change them
A visual representation
integer1 45
27
Reserved Words
28
Decision Making: Equality and Relational Operators
if (condition)
{
statement1;
}
if conditional
◦ If a condition is true, then the body of the if statement executed
◦ 0 is false, non-zero is true
◦ Control always resumes after the if structure
29
Decision Making: Equality and Relational Operators
if (condition)
{
statement1;
}
else
{
statement2;
}
The else body is executed if the condition is false
30
Decision Making: Equality and Relational Operators
31
Practice
◦ Write a C program that reads two integers and checks if they are equal
Enter two integers, and I will tell you
whether they are equal: 3 7
3 is not equal to 7
Enter two integers, and I will tell you
whether they are equal: 4 4
4 is equal to 4
◦ Online compiler: www.onlinegdb.com/online_c_compiler
Run locally on the machine the following command:
! gcc -o hello hello.c OR gcc –o hello.out hello.c
! The -o op on speci es the name to be assigned to the compiled/executable
program.
2.Run the following on the terminal:
! ./hello OR ./hello.out
GCC(GNU Compiler Collec on): A compiler.
32
ti
fi
ti
Practice
1 /*
2 Using if statements, relational
3 operators, and equality operators */
4 #include <stdio.h>
5
6 int main()
7 {
8 int num1, num2;
9
10 printf( "Enter two integers, and I will tell you\n" );
11 printf( “whether they are equal: " );
12 scanf( “%d %d", &num1, &num2 ); /* read two integers */
13
14 if ( num1 == num2 )
15 printf( "%d is equal to %d\n", num1, num2 );
16
17 if ( num1 != num2 )
18 printf( "%d is not equal to %d\n", num1, num2 );
19
20 return 0; /* indicate program ended successfully */
35 }
33
Arithmetic
Arithmetic operations
◦ + for addition
◦ - for substruction
◦ * for multiplication
◦ / for division
◦ % for remainder
◦ 7 % 5 evaluates to 2
Operator precedence
◦ Some arithmetic operators act before others (i.e., multiplication
before addition)
◦ Use parenthesis when needed
◦ Example: Find the average of three variables a, b and c
◦ Do not use: a + b + c / 3
◦ Use: (a + b + c ) / 3
34
Arithmetic
Rules of operator precedence:
35
Arithmetic
Full table of operator precedence (Table 2-1 in Chap.2 of the C textbook)
Unary
Bitwise operations
{
How are the following evaluated?
x & MASK == 0 equivalent to x & (MASK == 0)
equivalent to
1+x*2 1 + (x * 2)
36
Common Bugs
37
Order of Evaluation of Arguments
What is the expected result?
n = 1;
printf("%d %d\n", ++n, power(2, n));
• The order in which function arguments are evaluated is not specified in C
• The compiler can choose in which order to evaluate them
• Better avoid this to avoid bugs (and compiler-dependent behavior)
• Another example
x = f() + g();
• The compiler can evaluate either f() first or g() first
38
Common Bugs
What is the problem?
n = 1;
if (n = 1)
printf(“Cool!”);
Problem: use of “=“ instead of “==“
“=“ should be used for assignments while “==“ is used in conditionals
The previous code should be
n = 1;
if (n == 1)
printf(“Cool!”);
39
Common Bugs
What is the problem?
1 /*
2 Using if statements, relational
3 operators, and equality operators */
4 #include <stdio.h>
5
6 int main()
7 {
8 int num1, num2;
9
10 printf( "Enter two integers\n" );
11
12 scanf( “%d %d", num1, num2 ); /* read two integers */
13
14 if ( num1 == num2 ) No “&”
15 printf( "%d is equal to %d\n", num1, num2 );
16
17 if ( num1 != num2 )
18 printf( "%d is not equal to %d\n", num1, num2 );
19
20 return 0; /* indicate program ended successfully */
35 }
40
Common Bugs
What is the problem?
1 /*
2 Using if statements, relational
3 operators, and equality operators */
4 #include <stdio.h>
5
6 int main()
7 {
8 int num1, num2;
9
10 printf( "Enter two integers\n" );
11
12 scanf( “%d %d", &num1, &num2 ); /* read two integers */
13
14 if ( num1 == num2 )
15 printf( "%d is equal to %d\n", num1, num2 );
16
17 if ( num1 != num2 )
18 printf( "%d is not equal to %d\n", num1, num2 );
19
20 return 0; /* indicate program ended successfully */
35 }
41
Practice (Function Call)
42
Practice
Write a C program that contains two func ons:
The rst func on converts the input length from meter
to kilometer
The second func on converts the input temperature
from Fahrenheit to Celsius:
T (c) = (T (f) –32 ) * 5/9
Inside the main call these two methods
Hardcode the inputs for now.
43
fi
ti
ti
ti
Practice
44
Practice
Write a C program that scans a number “n” from
the user and prints all even numbers from 1 to
“n”
45
Practice
46
Practice (Command Line)
Write a C program that nds and prints the
maximum between three numbers. Scan one
number from the user and pass two numbers as
command line arguments. You should write and
use a func on nd_max() to nd the maximum.
47
ti
fi
fi
fi
Practice (Reading from Command Line)
48
Pointers
What are pointers?
As the name implies, a pointer “points” to a loca on in memory. They are
variables that store memory addresses.
For what purposes?
Retrieving value stored in memory loca on
Passing large objects without copying them
Accessing dynamically allocated memory
Referring to func ons
Nota ons used with pointers
& " address of operator
* " dereference operator
Declara on of a pointer
<variable_type> *<name>;
49
ti
ti
ti
ti
ti
Practice (Pointers)
50
Practice (Pointers)
51
Practice (Pointers)
52
Practice (Pointers)
53
Practice (Pointers)
54
Practice (Pointers)
55
C Parameters Passing
By value:
A duplicate copy of the argument is created and passed to the
called func on.
Any update of the variable inside the func on wont a ect the
original variable.
By reference
The address of the variable is passed to the called func on.
Any update of the variable inside the func on will a ect the
original value since the value is directly changed in its exact
memory loca on.
56
ti
ti
ti
ti
ff
ff
ti
Practice (Parameter Passing)
57
Arrays
58
Practice (Arrays)
59
Practice (Arrays)
60
Practice (Arrays)
Write a C program that searches for a number in an
array of integers using the following function’s
signature: bool search(int A[], int num, int size).
61
Practice (Arrays)
62
Strings
63
Strings
64
Strings
65
Practice (Strings)
66
Structures
67
Structures (Practice)
68
Structures (Practice)
69
Structures (Practice)
70
Structures (Practice)
71
Structures (Practice)
72
Dynamic Memory Allocation (using malloc)
73
Dynamic Memory Allocation (using malloc)
74
Dynamic Memory Allocation (using malloc)
75
Dynamic Memory Allocation (using malloc)
76
Dynamic Memory Allocation (using malloc)
77
Dynamic Memory Allocation (using malloc)
78