0% found this document useful (0 votes)
4 views24 pages

Introduction to C Programming Basics

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

Introduction to C Programming Basics

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

C LANGUAGE

INTRODUCTION
CSSE 120—Rose Hulman Institute of Technology
The C Programming
g g Language
g g
Invented in 1972 by y Dennis Ritchie at AT&T Bell
Labs.
Has been the main development language for UNIX
operating systems and utilities for a couple of
decades.
O Python
Our P th interpreter
i t t was written
itt iin C!
Used for serious coding on just about every
development platform.
platform
Especially used for embedded software systems.
Is usually compiled to native machine code.
code
† Faster and less portable than Python or Java.
Why
y C in CSSE 120?
Practical
† Several upper-level courses in CSSE, ECE, and Math
expect students to program in C.
† None of these courses is a prerequisite for the others.

† So each instructor has a difficult choice:


„ Teach students the basics of C, which may be redundant for
many of them who already know it, or
„ Expect students to learn it on their own
own, which is difficult for
the other students.
†A brief C introduction here will make it easier for you
y
(and your instructor!) when you take those courses.
Why
y C in CSSE 120?
Pedagogical
† Comparing and contrasting two languages is a good
way to reinforce your programming knowledge.
† Seeing programming at C's "lower-level" view than
Python's can help increase your understanding of what
really goes on in computing.
† Many other programming languages (notably Java,
C++ and C#) share much of their syntax and
C++,
semantics with C.
„ Learning
g those languages
g g will be easier after you
y have
studied C.
Our Textbook
Schildt s “C:
Schildt’s C: The Complete Reference”
Reference
It is a reference book, intended to be useful to you
in later courses
† Pro:easy to pick up and start reading at any point
† Con: is written with experienced programmers in mind
Classic C text/reference
/

Pretty amazing for a 20-year-old programming book!


For comparison, Harry Potter #3's rank is 25,578.
Some C Language
g g trade-offs
Programmer has more control, but fewer high high-level
level
language features to use.
Strong typing makes it easier to catch programmer
errors, but there is the extra work of declaring
types
yp of things g
Lists and classes are not built-in, but arrays and
structs can be very efficient
† and a bit more of a pain for the programmer.

New feature: quiz #s on slidesÆ Q1


from math import *

def printRootTable(n):
Parallel
f
for i in
i range(1,n):
(1 ) examples
print " %2d %7.3f" % (i, sqrt(i))
in Python
def main():
printRootTable(10) and C.
C
main()
#include <stdio.h>
#include <math.h>

void printRootTable(int n) {
int i;
for (i=1; i<=n; i++) {
printf(" %2d %7.3f\n", i, sqrt(i));
}
}
int main() {
printRootTable(10);
i tR tT bl (10)
return 0;
}
Q2-3
Recap:
p Comments in C
Python comments begin with # and continue until the
end of the line.
C comments begin with / /* and end with */.
/.
They can span any number of lines.
Some C compilers (including the one we are using)
also allow single-line comments that begin with //.
String
g constants in C
In Python, character strings can be surrounded by
single quotes (apostrophes), or double quotes
(quotation marks).)
(q
In C, only double quotes can surround strings (whose
type
yp in C is char*).)
† char *s = "This is a string";
printf(s); /* more about printf() soon */
Single quotes indicate a single character, which is not the
same as a string whose length is 1. Details later.
† char
h c = '
'x';
'
printf("%c\n", c);
Q4
printf statement
p
C: printf(" %2d %7.3f\n", i, sqrt(i));

Python equivalent: print " %2d %7.3f" % (i, sqrt(i))

printf s first parameter is used as a format string.


printf's string
The values of printf's other parameters are
converted to strings and substituted for the
conversion codes in the format string.
printf does not automatically print a newline at the
end.
printf – frequently
p q y used conversion codes
code data type Example
d decimal int x=4, y=5;
(int, long) printf("nums %3d, %d%d\n", x, y, x+y");
/*prints nums 4, 59*/
f real float p = 1
1.3/9,
3/9 q = 22.875;
875;
(float) printf ("%7.4f %0.3f %1.0f %f\n", p, p, q, q);
/* prints 0.1444 0.144 3 2.875000 */
lf real (double) double p = 1.3/9, q = 2.875;
printf
i tf ("%7.4f
("%7 4f %0
%0.3f
3f %1
%1.0f
0f %f\
%f\n",
" p, p, q, q);
)
/* prints 0.1444 0.144 3 2.875000 */
c character char letter = (char)('a' + 4);
(char) printf ("%c %d\n", letter, letter);
p
/* prints e 101 */
s string char *isString = "is";
(char *) printf("This %s my string\n", isString);
/* prints This is is my string! */
/ /
e real double c = 62345892478;
(scientific notation) printf("%0.2f %0.3e %14.1e", c, c, c);
62345892478.00 6.235e+010 6.2e+010
Getting
g Values from Functions
Just like in Python (almost)
Consider the function:
† double convertCtoF(double
( celsius)
) {
return 32.0 + 9.0 * celsius / 5.0;
}
H would
How ld we gett resultlt from
f a function
f ti in i Python?
P th ?
† fahr = convertCtoF(20.0)
Wh ' different
What's diff in
i C?
† Need to declare the type of fahr
† Need
N d a semi-colon
i l

Q5
Use If Statements or Else
if m % 2 == 0: if (m % 2 == 0) {
print "even" printf("even");
else: } else {
print "odd" printf("odd");
}
Python: C:
† Colons and indenting † Parentheses, braces
Or Else What?
if gpa > 2.0: if (gpa > 2.0) {
print "safe" printf("safe");
elif gpa >= 1.0: } else if (gpa >= 1.0) {
print "trouble" printf("trouble");
else: } else {
print "sqrt club" printf("sqrt club");
}
Python: C:
† Colons and indenting † Parentheses, braces
† elif † else if
Q6
Optional
p Braces
Braces group statements
Can omit for single
statement bodies
if (gpa > 2.0)
printf( safe );
printf("safe");
else if (gpa >= 1.0)
printf("trouble");
else
printf("sqrt club");
Danger,
g , Will Robinson!
What is printed in each if (n > 0)
case? if (a > 0)
Case n a printf("X");
1 1 1 else
2 -1 1 printf("Y");
3 1 -1
4 -1 -1
else goes with closest if Use braces
U b to
avoid confusion!
Indenting does not matter
to the compiler but use for
code readability!
Ahh. That's better!
What is printed in each if (n > 0) {
case? if (a > 0)
Case n a printf("X");
1 1 1 } else {
2 -1 1 printf("Y");
3 1 -1 }
4 -1 -1
Use braces
U b to
avoid confusion!
Does C have a boolean type?
yp 0
Enter the following C code in Eclipse:
void testBoolean(int n, int m) {
int p = n < m;
printf("Is
i tf("I %d lless th
than %d? %d\
%d\n",
" n,
m, p);
}
Add a couple of test calls to your main() function:
testBoolean(2,3); testBoolean(3,2);
0 in C is like False in Python
All other numbers are like True
Boolean operators
p in C
Python uses the words and, or, not for these
Boolean operators. C uses symbols:
† && means "and“
† || means "or“

† ! means "not“

Example uses:
† if ( >= 3 && a <= 5)) { … }
(a
† if (!same (v1, v2)) { …}

Q7
I Could While Away
y the Hours
How do you suppose the following Python code
would be written in C?
while n != 0:
n=n–1
print n
How do you break out of a loop in Python?
How do you suppose you break out of a loop in C?

Q8
A Little Input,
p , Please
To read input from user in C, use scanf()
Syntax: scanf(<formatString>, <pointer>, …)
Example:
int age;
scanf("%d",
scanf( %d , &age);
Another Example
p Pushes prompt string
to user before
b f asking
ki
for input.
To read input from user in C, use scanf()
Syntax: scanf(<formatString>, <pointer>, …)
Example:
double f, g;
printf("Enter two real numbers separated by a comma:");
fflush(stdout);
scanf("%lf,%lf", &f, &g);
printf("Average:
printf( Average: %5.2f\n",
%5.2f\n , (f + g)/2.0);

Comma is matched
ell-eff = "long
g float" against user input
Why not d for double?
Q9,10
Rectangular
g output
p in C
#include <stdio.h>
void rectangleSameNumEachRow(int numRows, int numCols) {
int i, j;
for (i=1; i<= numRows; i++) {
Output:
for (j
(j=1;
1; j<=numCols;
j< numCols; j++) { 11111111
printf ("%d", i); 22222222
}
printf ("\n");
33333333
}
}
int main() {
rectangleSameNumEachRow(3,
g ( , 8);
)
}
It's easier than Python because printf() does not
automatically add spaces like Python's
Python s print.
print
HW: try to finish nested loops (due next class), start
thatsPerfect (due in 2 classes)

You might also like