Algorithm Analysis
We read words until the end of the file and count them.
Algorithm Implementation
Declare a working array.
char s[300];
Count the number of words in the variable cnt
.
cnt = 0;
Read the input data until the end of the file. After each read word s
, we increase cnt
by 1.
while(scanf("%s",s) == 1) cnt++;
Output the answer.
printf("%d\n",cnt);
Algorithm Implementation – string
Count the number of words in the variable cnt
.
cnt = 0;
Read the input data until the end of the file. After each read word s
, we increase cnt
by 1.
while(cin >> s) cnt++;
Output the answer.
cout << cnt << endl;
Java Implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); int cnt = 0; while(con.hasNext()) { con.next(); cnt++; } System.out.println(cnt); con.close(); } }
Python Implementation
Read the input string. Convert it into a list of words. Calculate the length of the list res
.
res = len(input().split())
Output the answer.
print(res)