Classes/csci218/Lect/101.c

116 lines
2.3 KiB
C

//Array, Loop, and C string
#include <stdio.h>
void iniArray();
void evenNums();
void oddNums();
void copyArray();
void Cstring();
int main()
{
//iniArray();
//evenNums();
//oddNums();
//copyArray();
Cstring();
return 0;
}
void iniArray(){
printf("\nThis function ask values of array x one by one from user.\n");
const int N = 5;
//declare an integer array x of N elements
int x[N];
int len = sizeof(x)/sizeof(x[0]);
//ask user to enter the values of elements
for (int i = 0; i < len; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &x[i]);
}
//display all the values of x
printf("Array x[%d] has values: {", len);
for (int i = 0; i < len-1; i++) {
printf("%d, ", x[i]);
}
printf("%d}\n", x[len-1]);
}
void evenNums(){
printf("\nThe function will store 10 even numbers starting from 0 to array A. Print the array\n");
//declare variables
int A[10];
for (int i = 0; i < 10; i++) {
A[i] = i * 2 + 4;
}
for (int i = 0; i < 10; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void oddNums(){
printf("\nThe function will store 10 odd numbers starting from 1 to array A. Print the array\n");
//declare variables
int A[10];
for (int i = 0; i < 10; i++) {
A[i] = i * 2 + 1;
}
for (int i = 0; i < 10; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void copyArray(){
printf("\nThis function copy element of array A to array B.\n");
int A[] = {2, 4, 6, 8}; // A is an integer array of length 4
int B[3];
int i; // loop index
//copy and print B
int lenB = sizeof(B)/sizeof(B[0]);
int lenA = sizeof(A)/sizeof(A[0]);
for (int i = lenA - lenB; i < lenA; i++) {
B[i] = A[i];
printf("%d ", B[i]);
}
printf("\n");
//print A
for (int i = 0; i < lenA; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void Cstring(){
printf("\nThis function is for you to learn C string.\n");
//declare an array of charaters
char x[] = {'g', 'a', 'r', 'r', 'e', 't', 't', '\0'};
printf("x = %s, size = %lu\n", x, sizeof(x));
//declare a C string y using " "
char y[] = "Hello There";
printf("y = %s, size = %lu\n", y, sizeof(y));
//declare a C string z using { }, '\0' indicate the end of string
char z[] = {'A', 'B', 'C', '\0'};
printf("z = %s, size = %lu\n", z, sizeof(z));
for (int i = 0; x[i]; i++) {
printf("%c\n", x[i]);
}
}