CS140: Intro to CS

An Overview of Programming in C (part 3)

by Erin Chambers

Getting started

Please log in to the computer, click on the startup menu (located in bottom left corner)

Select “Utilities” -> “Kate” to open a text editor

Running our program

We need to compile our C program using the compiler called cc

The compiler then outputs an executable file which will run our program, usually called a.out

To run it, open up a Konsole (the little black screen icon at the bottom), type “cc filename.c”, then type “./a.out” at a command prompt

Recap

Numbers - int, float

Output – printf

Input - scanf

If-else statements

While loops

Characters - char

Characters

The data type char stores a single character

Each character is actually represented as a number, just like with ASCII

To read or write a character variable, use %c

Basic char program

#include <stdio.h>

main(void)

{

char letter;

printf(“Enter a character:”);

scanf(“%c”,&letter);

printf(“You entered %c”, letter);

return 0;

}

Fun with char

#include <stdio.h>

main(void)

{

char letter; \\initialize letter to be a character

\\Read in a character

printf(“Enter a character:”);

scanf(“%c”, &letter);

\\Print out the character and its associated number

printf(“The character you entered is %c \n”, letter);

printf(“Its C number is %d”, letter);

return 0;

}

Char tricks

#include <stdio.h>

main(void)

{

char letter;

int number;

//Prompt user to enter a character

printf("Enter a letter:");

scanf("%c", &letter);

//Find the next letter in the alphabet and print it

number = letter;

number = number + 1;

printf("The next letter is %c\n", number);

return 0;

}

A shortcut

The c command “getchar()” reads the next character from the input

So

letter = getchar();

is equivalent to

scanf(“%c”, &letter);

Count the length of a message

#include <stdio.h>

main(void)

{

char ch;

int length = 0;

//Prompt the user for a message

//Read the first character of the message

//while loop to count how the message is

//print length of message

return 0;

}

2008-10-03T15:06:49